1

I have written my custom module for Drupal 7. In my page_change.module file I have only:

<?php
    drupal_add_js(drupal_get_path('module', 'page_change') . '/page_change.js');
?>

In my page_change.js file I have only:

Drupal.behaviors.page_change = {
    attach: function (context) {
        console.log("text");
    }
};

As soon as I enable my module, Drupal doesn't load jquery.js. It does not even appear in html source in <head> section. When I disable my module, or delete the only line from page_change.module file everything works fine.

I have also tried to load my javascript file by adding

scripts[] = page_change.js

In my page_change.info file (and leaving page_change.module with only <?php ?>) but it doesn't seem to work either.

Why does that happen? What am I doing wrong? Am I missing something?

edit: I have even tried to add inline javascript by adding

drupal_add_js('console.log("text");', array('type' => 'inline', 'scope' => 'footer'));

and it writes text to console, but jquery.js is still missing.

0

Ok, somehow I forced it to work, but I still have no idea why it hadn't work before.

I have changed my page_change.module contents to:

<?php
function page_change_preprocess_page(&$variables) {
    $file = drupal_get_path('module', 'page_change').'/page_change.js';
    $options = array(
      'weight' => 1000,
      'scope' => 'footer'
    );
    drupal_add_js($file, $options);
}
?>

then I disabled and enabled my module and miraculously it works.

If you have any idea why I had these problems, please post your answer.

1
  • I had this issue and by changing the hook to hook_init() worked. If you don't mind having this fire right away instead of when preprocess_page fires, I have a feeling it would work. It did for me! :) Mar 11 '14 at 19:16
0

Your custom JS should be wrapped in:

(function($) {
  // custom Drupal behaviors here
})(jQuery);

Give that a shot.

2
  • I do not use jQuery in my javascript. I've tried this, it doesn't help. Problem is that Drupal does not load jQuery when I add any javascript, not the javascript itself. Javascript works perfectly. Sep 12 '13 at 17:32
  • Yes, this issue is actually with what Drupal outputs in the source. jQuery.js is not output in this case. Mar 11 '14 at 19:18

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.