Category Archives: Javascript

JQuery – Passing an Attribute Object

As of jQuery 1.4, we can now pass an object as the second parameter of the jQuery function. This is helpful when we need to insert new elements into the DOM. For example:

Before

    $('')
      .attr({
        id : 'someId',
        className : 'someClass',
        href : 'somePath.html'
      });

After

    $('', {
        id : 'someId',
        className : 'someClass',
        href : 'somePath.html'
    });

Not only does this save a few characters, but it also makes for cleaner code. In addition to element attributes, we can even pass jQuery specific attributes and events, like click or text.

JQuery – A Single Hover Function

As of jQuery 1.4, we can now pass only a single function to the hover method. Before, both the in and out methods were required.

Before

$('#someElement').hover(function() {
// mouseover
}, function() {
// mouseout
});

Now

 $('#someElement').hover(function() {
 // the toggle() method can be used here, if applicable
 });
 

Note that this isn’t an old vs. new deal. Many times, you’ll still need to pass two functions to hover, and that’s perfectly acceptable. However, if you only need to toggle some element (or something like that), passing a single anonymous function will save a handful of characters or so!

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.
j('#someDiv').hide();

// 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
})(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.