Madhu
Madhu

Reputation: 147

JQuery same function for multiple events (ex: hover and click event)

is there any way to execute same code for different events on the page?

$('.class1').hover(function() {
   some_function();
});

$('.class1').click(function() {
   some_function();
});

instead to do something like:

$('.class1').click.hover(function() {
   some_function();
});

Upvotes: 0

Views: 2675

Answers (2)

Mario Menger
Mario Menger

Reputation: 5902

While bind is the way to go if you want to attach the event handlers at the same point in your code using the same selector, if you want to attach them at different points or using different selectors, you could always just use a named function, rather than an anonymous one:

function someWrappingFunction() {
   some_function();
}

$('.class1').hover(someWrappingFunction); 

$('.class1, .anotherClass').click(someWrappingFunction); 

Upvotes: 5

Andy E
Andy E

Reputation: 344675

Use bind():

$('.class1').bind("click hover", function() {
   some_function();
});

Upvotes: 11

Related Questions