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?
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.
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.
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.
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.
you can use both :
(function( $ ){
})( jQuery.noConflict() );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With