JQuery – Keep your Code Safe

If developing code for distribution, it’s always important to compensate for any possible name clashing. What would happen if some script, imported after yours, also had a $ function? Bad stuff!

The 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.

Method 1: NoConflict

var j = jQuery.noConflict();
// Now, instead of $, we use j.

// The line below will reference some other library's $ function.
$('someDiv').style.display = 'none';

Be careful with this method, and try not to use it when distributing your code. It would really confuse the user of your script! 🙂

Method 2: Passing jQuery

(function($) {
// Within this function, $ will always refer to jQuery

The final parens at the bottom call the function automatically – function(){}(). However, when we call the function, we also pass jQuery, which is then represented by $.

Method 3: Passing $ via the Ready Method

jQuery(document).ready(function($) {
// $ refers to jQuery

// $ is either undefined, or refers to some other library's function.

Leave a Reply

Your email address will not be published. Required fields are marked *