17

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($){...})?

3 Answers 3

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 :)

2
  • 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
    Commented Feb 20, 2013 at 16:56
  • make that var $ = jQuery;
    – commonpike
    Commented Oct 26, 2014 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 :)

5
  • 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($){…}).
    – avpaderno
    Commented Apr 22, 2011 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
    Commented Apr 22, 2011 at 21:34
  • @maxedison what happens when you mix PHP with JavaScript? Use dollar signs in text strings manipulated by JavaScript?
    – user7
    Commented Apr 22, 2011 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
    Commented Oct 3, 2011 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.
    – aendra
    Commented Dec 13, 2012 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 and acknowledge you have read our privacy policy.

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