Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - No Conflict or closure

Tags:

jquery

I am writing an application at the moment that uses jquery. It fits in to an existing application that uses prototype so obviously I cant use the dollar sign straight away.

I have been using noconflict to get around this but couldnt I just wrap my whole script inside a closure passing in jquery as in:

(function( $ ){

})( jQuery );

This seems to work but I am wondering if there are any consequences to this?

like image 583
David Avatar asked Feb 26 '11 13:02

David


People also ask

What is jQuery no conflict?

The noConflict() method releases jQuery's control of the $ variable. This method can also be used to specify a new custom name for the jQuery variable. Tip: This method is useful when other JavaScript libraries use the $ for their functions.

What can I use instead of jQuery?

Javascript Nevertheless, Native javascript is one of the best jQuery alternatives, in fact, It is the framework of JS. Javascript is the best because any browsers ships with javascript and you do not need to install jQuery in your application.

What is function ($) jQuery?

It's bed time here, but just for starters, (function($) { })(jQuery); wraps the code so that $ is jQuery inside that closure, even if $ means something else outside of it, usually as the result of $. noConflict() for example.

What is no conflict?

jQuery - noConflict() Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all the functionality is available without using $. Run $. noConflict() method to give control of the $ variable back to whichever library first implemented it.


2 Answers

you can use both :

(function( $ ){

})( jQuery.noConflict() );
like image 106
gion_13 Avatar answered Sep 22 '22 04:09

gion_13


That should work fine, since your passing jQuery into your closure as the jQuery object itself.

The noConflict should still be specified though - otherwise the jQuery object could take control of the dollar sign. Calling noConflict passes the dollar sign back to anything that is already using it.

The documentation suggests this too:

  $.noConflict();
  jQuery(document).ready(function($) {
    // Code that uses jQuery's $ can follow here.
  });
  // Code that uses other library's $ can follow here.
like image 22
Jonathon Bolster Avatar answered Sep 24 '22 04:09

Jonathon Bolster