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?

  • 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? – AyeshK Oct 20 '12 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 '12 at 18:03
  • 1
    I don't have any problems with jQuery Update and Panels. – mpdonadio Oct 20 '12 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 '12 at 20:32

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 acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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