0

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();
});
3
  • Reconsider your question for syntax errors, please. Commented Aug 5, 2010 at 10:00
  • possible duplicate of jquery combine event functions
    – jAndy
    Commented Aug 5, 2010 at 10:01
  • These are not different elements, these are different events. Commented Aug 5, 2010 at 10:03

2 Answers 2

11

Use bind():

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

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); 
1
  • excellent. thank you. Also note that if you use $(document).ready(function(){ // event handlers });, you don't need a wrapping function. Just a function.
    – khaverim
    Commented May 17, 2014 at 1:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.