Alexander Graham
Alexander Graham

Reputation: 407

jQuery single handler for multiple events

$('div').mouseenter(function() {
    $(this).slideUp(150);
});

$('div').mouseenter(function() {
    $(this).slideDown(150);
});

How can I combine this into something smaller?
Don't know enough jQuery / JS for this yet.

Upvotes: 1

Views: 55

Answers (2)

George Kagan
George Kagan

Reputation: 6124

$('div').on('mouseenter mouseleave', function() { 
   ...
})

Another benefit of using .on() is event delegation, meaning any future divs will also trigger the events, instead of manually binding the event on them.

Upvotes: 2

mukesh kudi
mukesh kudi

Reputation: 729

You can use .on() to bind a function to multiple events:

$('div').on('event1 event2', function(e) {
 $(this).slideToggle(150);
});

Upvotes: 3

Related Questions