Friday, January 23, 2015

jQuery - Pro Tip #2

jQuery - Pro Tip #2 - selector caching!


instead of repeating the selector and hence (re)traveling the DOM:

function doWork(){
    $('#divTag').addClass("has-error");
    $('#divTag').slideUp();
}

cache the selector - caching it outside the method allows for reuse in multiple methods.
var someDivTag = $('#divTag'); 
function doWork(){
   someDivTag.addClass("has-error");
    someDivTag.slideUp();
}
and finally chain it:

function doWork(){
   someDivTag.addClass("has-error").slideUp();
}

No comments:

Post a Comment