If you are developing code for free distribution or developing plugins for sale, it's always important to consider for any possible name/id conflict. What would happen if some script, imported after yours, also had a $ function like jQuery?
Most common answer is to either call jQuery's noConflict(), or to store your code within a self-invoking anonymous function, and then pass jQuery to it. It's bit nasty and will create problem in your future development. So, We need to know how to keep your code safe.
Today I'm going to share 3 super simple ways to keep your code safe. Let's go-
Most super simple way to avoid conflict. Be careful with this method, and try not to use it when distributing your code. It would really confuse the user of your script!
var j = jQuery.noConflict();
//Instead of $, we use j or any other word as you want.
j('#someDiv').hide();
// The line below will reference some other library's $ function.
$('someDiv').style.display = 'none';
The final parameter at the bottom call the function automatically– function(){}(). However, when we call the function, we also pass jQuery, which is then represented by $.
(function($) {
// Within this function, $ will always refer to jQuery
})(jQuery);
jQuery(document).ready(function($) {
// $ refers to jQuery
});
//$ is either undefined, or refers to some other library's function.
Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!
You might also like...
Unordered list sequential fade in and fade out effect in jquery
Mega Collection of jQuery Social Networking Plugins
Page redirection with Live time left preview using jquery
Md Mahbub Alam Khan is the Editor and Founder of CoolAJAX Web Blog. You can follow CoolAJAX on Twitter , on Facebook or you can subscribe via RSS .
Topics