Question

I'd like to use jQuery to perform one single operation when one of the events happen, rather how to optimize this code:

$("#selector").on('click', function(){
 alert(1);
});

$("#selector").on('hover', function(){
 alert(1);
});

$("#selector").on('blur', function(){
 alert(1);
});

You see where I'm going with this. Basically it's one same functions but it's only the different triggers. Is there any way to stop me being redundant and wrap all this more simple?

Was it helpful?

Solution

With multiple selector chaining

$('#element').on('click hover blur', function() {
    ...
});

You can also select multiple classes:

$('#foo, #bar, #element').on('click hover blur', function() {
    ...
});

OTHER TIPS

$('#element').on('click hover blur', function() {
    ...
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top