1

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');
        }
    }

});
CD Smith
  • 6,597
  • 7
  • 40
  • 66
PruitIgoe
  • 6,166
  • 16
  • 70
  • 137
  • As already answered, second one is better, also it is recommended that you use `===` instead of `==` in the if conditions. – gopi1410 Jun 20 '12 at 19:54
  • Possible duplicate: http://stackoverflow.com/questions/10433014/what-is-the-cost-of-this – Josh Mein Jun 20 '12 at 19:54
  • You are splitting hairs. I agree, the second way is better but the first way is clearer. Pick one way and stick with that format throughout your program. – MMeah Jun 20 '12 at 20:05

3 Answers3

6

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');
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

You can use .slideToggle() too

$(".topHorzNavLink").click(function() {

    var theHoverContainer = $("#hoverContainer");

    var thisHorzLink = $(this).attr('linkItem');

    if (thisHorzLink == "link2") {

            theHoverContainer.slideToggle('slow');
    }

});
Prasenjit Kumar Nag
  • 13,391
  • 3
  • 45
  • 57
1

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.

MMeah
  • 1,032
  • 1
  • 9
  • 18