for admin work good!

for test i just write this:


Thanks for any help -)

UPDATE: my JS file attached to tag but code not run, any js code not run in any place... fo anonymous, for admin work fine

  • 1
    How are you adding javascript ? Using #attached, or some way ? – AyeshK Feb 23 '14 at 18:46
  • in page.html.twig wrap with tags <script>, also iclunde from .info.yml – OnengLar Feb 23 '14 at 18:49

First of all, you should avoid using .ready(), you should use Drupal.behaviors mechanism like this:

(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {

This might also be the problem why it does not work for anonymous. See documentation for more details.

You also need to add the .js file correctly, if it should be in theme then you need to add it in the .info file like this: scripts[] = somescript.js

See more in the documentation already posted.

Edit: I found this presentation on D8 js changes, it could be helpful. It shows how to add js by implementing hook_library_info and #attach (slide 18)

| improve this answer | |
  • thanks for reply) but not work yep, also i add to .info.yml file, it's first what i try) – OnengLar Feb 23 '14 at 18:55
  • I updated the answer, check if the file is correctly added (use inspect element or view source code of your browser) – m1n0 Feb 23 '14 at 18:58
  • 3
    drupal_add_js() is a no go for D8. You have to use renderable stuff. – AyeshK Feb 23 '14 at 18:59
  • I updated my answer with more d8 stuff – m1n0 Feb 23 '14 at 19:08
  • OK, js doesn't work even if i put js to bartik theme... thanks for help, I will wait for Drupal 8 release =)) – OnengLar Feb 23 '14 at 19:37

Adding js files to your module or theme alone won't work because pages no longer need to load with drupal.js (or jquery for that matter). A lot of work went into making the front end faster that this is one of the decisions. You need to actually add the jquery library to your page to be able to use the library and this can be done by either converting your js into a library that depends on jquery (as m1n0 answered above), or by attaching the jquery library to your page build followed by attaching your js. The latter would be something like the following:

 * Implements hook_page_build().
function MYMODULE_page_build(&$page) {
  $path = drupal_get_path('module', 'MYMODULE');
  // Attach libraries (which is in an array format of LIBRARY_NAME, COMPONENT_NAME)
  $page['#attached']['library'][] = array(
    'core', 'jquery'
  $page['#attached']['js'][$path . '/mymodule.script.js'] = array('every page' => TRUE);
  $page['#attached']['css'][$path . '/mymodule.base.css'] = array('every_page' => TRUE);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.