Reputation: 6384
Is there any difference between doing this:
$(".topHorzNavLink").click(function() {
var theHoverContainer = $("#hoverContainer");
var thisHorzLink = $(this).attr('linkItem');
if (thisHorzLink == "link2") {
if ($("#hoverContainer").is(":visible") == true) {
$("#hoverContainer").slideUp('slow');
} else {
$("#hoverContainer").slideDown('slow');
}
}
});
or this:
$(".topHorzNavLink").click(function() {
var theHoverContainer = $("#hoverContainer");
var thisHorzLink = $(this).attr('linkItem');
if (thisHorzLink == "link2") {
if (theHoverContainer.is(":visible") == true) {
theHoverContainer.slideUp('slow');
} else {
theHoverContainer.slideDown('slow');
}
}
});
Upvotes: 1
Views: 76
Reputation: 707218
Your second method is more efficient because it runs the selector operation $("#hoverContainer")
only once and uses the same jQuery object over and over rather than run the same selector operation three times and construct three new jQuery objects each time.
For compactness and efficiency, you could do this:
$(".topHorzNavLink").click(function() {
if ($(this).attr('linkItem') == "link2") {
$("#hoverContainer").slideToggle('slow');
}
});
Or, if the linkItem
attribute is not dynamically assigned/changed, you could bake it into the selector like this:
$(".topHorzNavLink[linkItem='link2']").click(function() {
$("#hoverContainer").slideToggle('slow');
});
Upvotes: 6
Reputation: 1042
They are more or less the same speed. jQuery has already optimized the ID selector by looking for "#" and doing a document.getElementById on that id. Unless you are running this function 1000s of times, you will not see a dramatic speed improvement.
I would take whatever approach you are most comfortable with. The first way is clearer on what you are selecting. The second way defines the selector only once, therefore making it easier to modify later.
Upvotes: 1
Reputation: 13461
You can use .slideToggle()
too
$(".topHorzNavLink").click(function() {
var theHoverContainer = $("#hoverContainer");
var thisHorzLink = $(this).attr('linkItem');
if (thisHorzLink == "link2") {
theHoverContainer.slideToggle('slow');
}
});
Upvotes: 1