tags:

views:

36

answers:

3

i need to call the same function on many events

$("#test1").click(function(){
some_function();
});
$("#test1").hover(function(){
some_function();
})

how can i write this with one function?

Thnaks

+2  A: 

You could put all the events in an array, and for each element add your function.

Example:

events=[ $("#test1").click, $("#test1").hover ];

for ( e in events ) {
  e( some_function );
};
xtofl
+1  A: 

$('#test1').bind('click hover', function() { some_function(); });

http://api.jquery.com/bind/

dmitko
+3  A: 

That seems messy. I believe this should work.

$('#test1').bind('click mouseenter mouseleave', some_function);

Remember that .hover() takes two functions as arguments, so having only one function could produce unexpected results.

Squirkle
I would like to add you can use `event.type` (http://api.jquery.com/event.type/) to figure out which event was fired.
fudgey