18

If I'm not planning on using any JS libraries other than jQuery, is there any reason to need Drupal's call to jQuery.noConflict() which removes $ as an alias for jQuery?

Assuming there is no need for removing the $ alias, is there a way I can get it back universally without always having to wrap my jQuery code in (function($){...})?

11

The solution I came up with is this:

At the top of the first JS file I include in my custom theme, I simply put the following line:

$ = jQuery;

Done :)

  • Lol, thank you! I was trying to figure out why jQuery was defined, but $ was not. We should make that snippet into a module :D – CamelBlues Feb 20 '13 at 16:56
  • make that var $ = jQuery; – commonpike Oct 26 '14 at 18:32
6

No, you can not (Well, you probably could, but you shouldn't).

Maybe at some point, your module will be used on another project on another site and then that site will use another JS library (Remember, every drupal module you write is automatically GPL and your client can use it in any way they want).

It's not that complicated to add these two lines to every js file :)

  • I agree; for the sake of compatibility is better to not use $ as alias for jQuery, in Drupal, and always wrap JavaScript code using jQuery with (function($){…}). – kiamlaluno Apr 22 '11 at 21:30
  • At that point, it wouldn't be difficult to simply do a find and replace to turn all $ into jQuery in my module. – maxedison Apr 22 '11 at 21:34
  • @maxedison what happens when you mix PHP with JavaScript? Use dollar signs in text strings manipulated by JavaScript? – user7 Apr 22 '11 at 21:49
  • 1
    You totally ignored what the question asker was "assuming". It's a valid question and a hindurance, especially when embedding 3rd party plugins -- you need to edit all those files to get them to work without $, and you need to do it every update. Find and replace doesn't work with more complex plugins either, since they might require something to be global scope. Needs a fix tbh. – red Oct 3 '11 at 6:30
  • I'm trying to coin a phrase on the Internet: "Every time you use $(), God kills a kitten." Please -- think of the kittens. – aendrew Dec 13 '12 at 10:24
0

This could also be a possible solution, if you tend to use modules for those kind of questions.

jQuery Dollar

This module allows developers to use $ to access the jQuery library instead of having to call jQuery explicitly or use special closures in Drupal 7. All you have to do is enable it.

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.