1

I'm using drupal_add_js() to load some external js:

drupal_add_js('http://jquery-accordion.googlecode.com/svn/trunk/jquery.accordion.js', 'external');

This produces 'TypeError: $ is not a function' errors because Drupal uses jQuery in no-conflict mode.

So I think the only solution is to copy the code, wrap it in this function and call it locally:

(function ($) {
  // Original JavaScript code.
})(jQuery);

I wondered whether there was a trick to still be able to directly use external js?

4
  • Tried JQuery Update? You will be able to use a google-hosted jquery which I believe is correct one for your case. May be the counterpart - modifying the new js file?
    – AKS
    Oct 20, 2012 at 14:57
  • I've been avoiding JQuery Update because I think it breaks some things (Panels), but will give it a try.
    – pushka
    Oct 20, 2012 at 18:03
  • 1
    I don't have any problems with jQuery Update and Panels.
    – mpdonadio
    Oct 20, 2012 at 20:30
  • 2
    To be honest, the best option it to patch the external script, and send it to the author. jQuery best practice is to write the plugin so that it will work in no-conflict environments.
    – mpdonadio
    Oct 20, 2012 at 20:32

1 Answer 1

0

In Drupal 7, if you a certain that the external scripts are attempting to use "$" as an alias for jQuery, and you can't get the script author to patch their code, and you aren't loading any other JavaScript libraries, then in your template_preprocess_page, place the following drupal_add_js before the set of all drupal_add_js that reference external files. All scripts in the header region that use "$" as an alias will then refer to jQuery:

drupal_add_js('var $ = jQuery;', 'inline');

If your external javascript is added in another region, for example, the footer, then use something similar to the following instead:

drupal_add_js('var $ = jQuery;', array('type' => 'inline', 'scope' => 'footer'));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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