MeltingDog
MeltingDog

Reputation: 15414

When, if ever, should you use `jQuery` over `$`?

I was looking through some code and noticed:

button: function(e) {
  e.preventDefault();
  var $target = jQuery(e.target);
  var link = $target.attr('href');

I was just a little unclear about the line var $target = jQuery(e.target);.

Why use jQuery here?

Upvotes: 0

Views: 77

Answers (1)

Guillermo Gutiérrez
Guillermo Gutiérrez

Reputation: 17799

Usually you would like to use jQuery instead of $, when the latter conflicts with a globar variable from another library.

For instance, see this list: What JavaScript libraries are known to use the global dollar sign: window.$?

In that case, jQuery provides the noConflict() method, which:

Relinquish jQuery's control of the $ variable.

The documentation also states:

In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them.

Upvotes: 1

Related Questions