Matt
Matt

Reputation: 75

Which jQuery code is more efficient?

Out of curiousty which of the following code is more efficient (if neither, what would be the best way?)

Backstory - Building a small image carousel and the code in question has to do with the controls (prev, pause/play, next)

<ul class="controls"> 
    <li> <a href="#" class="prev">  Previous Image </a> </li>
    <li> <a href="#" class="pause"> Pause          </a> </li>
    <li> <a href="#" class="next">  Next Image     </a> </li>
</ul>

// inside document.ready()
$(".controls a").click(function() {
    var cur_class = $(this).attr("class");

    if (cur_class == "pause") {
        // do something
    } else if (cur_class == "prev") {
        // do something
    } else if (cur_class == "next") {
        // do something
    }
)};

// OR THIS
$(".controls a.prev").click(function() { /* do something */ });
$(".controls a.pause").click(function() { /* do something */ });
$(".controls a.next").click(function() { /* do something */ });

Thanks M.

Upvotes: 4

Views: 208

Answers (3)

jonagoldman
jonagoldman

Reputation: 8754

Best option is to use .delegate(). Its a new event added to jQuery 1.4.2 and its much better than just using click.

.click() adds a new event for every anchor tag.

.delegate() 'waits' for a click (or any event specified) to be made before adding a new event (for the specific clicked element only).

$(".controls").delegate("a", "click", function() {

    var cur_class = $(this).attr("class");

    if (cur_class == "pause") {
        // do something
    } else if (cur_class == "prev") {
        // do something
    } else if (cur_class == "next") {
        // do something
    }

}

Note: the code is not tested, read the .delegate() info in the jQuery documentation for more info.

Maybe you need to add an id to the <ul>:

(<ul class="controls" id="ul_id">) and then use $("#ul_id").delegate("a", "click", function() { / ... }.

Hope that helps.

Upvotes: 5

Jacob Relkin
Jacob Relkin

Reputation: 163248

I think the following is the fastest way. It only fetches a DOM nodelist once and filters it instead of fetching it three times

$('.controls a')
.filter('.prev')
.click(function(){/*...*/})
.end()
.filter('.pause')
.click(function(){/*...*/})
.end()
.filter('.next')
.click(function(){/*...*/});

Upvotes: 2

user347594
user347594

Reputation: 1296

Almost no difference. As your building a carousel the big bottleneck will be the images you load.

Upvotes: 4

Related Questions