I have multiple dropdown boxes which drop when their link is clicked. The boxes have the possibility to overlap if they are open at the same time.
Is it faster to qu
I think its faster to hide it always. Another option could be to create a reference for the box example var b = $('#box2'). rather than calling $('#box2'). I think this would be the best option.
You could use .toggle() function for this too.
var $box1 = $('#box1'),
$box2 = $('#box2');
$('.majorDiv').on('click', '#box1-link', function(e){
var $this = $(this);
e.preventDefault();
$box1.fadeToggle();
$box2.slideDown(200, function(){
//do stuff here
});
});
(August 2013) It looks like with the changes to jQuery, simply calling hide
may not be the fastest option anymore (though it's probably still preferable, for brevity, and clarity). Take a look at this updated benchmark test case.
The second approach, however, is likely to be faster simply because it already has that if
check built-in to it anyway:
// ... line 7996 (jQuery 1.8.1):
if (!values[index] && display !== "none") {
jQuery._data(elem, "olddisplay", display);
}
// ...
In other words, the function is only executed on the DOM element if it doesn't already have display: none
. There's could still be a possibility that the .is()
method manages to be a little faster since it avoids fewer method calls, but a look at the method itself will quickly dispel these fears:
// ...line 6804:
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test(selector) ?
jQuery(selector, this.context).index(this[0]) >= 0 :
jQuery.filter(selector, this).length > 0 :
this.filter(selector).length > 0);
// ...
In short, the second is faster -- jsPerf test-case.