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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With