Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same selector with multiple functions/event handlers

Tags:

jquery

pretty simple question here: is there a better way to write this code?

$('.icMenu span.menu').each(function() {
     // do something
});

$('.icMenu span.menu').click(function() {
    // do something else
});

I'm using the same selector twice, is there a better way I should be writing this?

like image 327
Ollie Clark Avatar asked Jan 31 '26 15:01

Ollie Clark


1 Answers

Options:

Use chaining as already suggested

$('.icMenu span.menu').each(function() {
     // do something
}).click(function() {
    // do something else
});

Or simply use a local variable to avoid running the jQuery selector twice:

var $menus = $('.icMenu span.menu');
$menus.each(function() {
     // do something
});
$menus.click(function() {
    // do something else
});

Basic rule:

The key is to always avoid running the selector more than once as that has a large overhead.

Delegated Events:

If your elements are ever dynamically created, you would move the click to a delegated on event handler anyway, so your question would become a non-issue (they would be the same selector, but separated in time):

$(document).on('click', '.icMenu span.menu', function(){
     // Do something on dynamically created elements
});

In a delegated event handler, the selector is only run after the event is caught on an ancestor (in this case document). The function is then applied to any matching elements that caused the event.

like image 129
Gone Coding Avatar answered Feb 02 '26 10:02

Gone Coding