0

I need to change javascript code of jCarousel, and I want to create my own function and change it in hook_js_alter(), but it is not working properly, or I missing something.

function common_js_alter(&$javascript) {
  if ($node = menu_get_object()) {
    if ($node->type == 'home') {
      if (array_key_exists('sites/all/libraries/jquery.jcarousel/lib/jquery.jcarousel.js', $javascript)) {
        $file = drupal_get_path('module', 'common') . '/js/jcarousel.js';
        $javascript['sites/all/libraries/jquery.jcarousel/lib/jquery.jcarousel.js'] = drupal_js_defaults($file);
        dpm($javascript);
      }
    }
  }
}

I need to change sites/all/libraries/jquery.jcarousel/lib/jquery.jcarousel.js to drupal_get_path('module', 'common') . '/js/jcarousel.js'. The path is correct, but as I can see with dpm() no scope is enabled and type.

3
  • You should just change $javascript['sites/all/libraries/jquery.jcarousel/lib/jquery.jcarousel.js']['data'], not all the other values. – kiamlaluno Nov 22 '12 at 16:09
  • i tried, but its not working, and i got an error Undefined index: scope in drupal_get_js() – Petro Popelyshko Nov 22 '12 at 16:11
  • 1
    Then something else is wrong, but not in that code. drupal_js_defaults() surely sets 'scope'. – kiamlaluno Nov 22 '12 at 16:15
3

Just got into this function too to alter "folder/js_file.js" and the issue causing the

Notice: Undefined index: scope in drupal_get_js() (line 4309 of [DRUPAL_DIR]\includes\common.inc).

error is that there are times when the hook is called but "folder/js_file.js" is not yet in the array w/c just adds

[folder/js_file.js] => Array(
  [data] => [your_custom_js],
)

to the array but the scope, type, and other attributes are not there. So we first need to check if the array key exists like so:

if (isset($javascript['folder/js_file.js'])) {
  $file = drupal_get_path('module', 'mymodule') . '/your_custom_js.js';
  $javascript['folder/js_file.js']['data'] = $file;
}

That solves it. :)

2
  • Nope, this doesn't work at all. – aaronbauman Mar 26 '15 at 15:55
  • While using drupal_js_defaults() as sugested in comments to question gives me bunch of other errors, this works great. – tdd Sep 4 '15 at 12:32

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.