skip to content

jQuery Edge: Simplified .hover()

2 min read

In jQuery 1.3.3 1.4 the .hover() method will optionally accept a single method instead of always requiring two methods. This allows you to contain your logic within one method instead of duplicating it among two. I don’t know about you but I’ve avoided using the .hover() method in favor of just manually binding the mouseenter and mouseleave events so that I could use a single function to handle both events. So, lets look at a typical use-case for hover.

$('li')
    .hover(function(event) {
        $(this).addClass('test');
    }, function(event) {
        $(this).removeClass('test');
    });

Now, this is how I’d typically handle this without the use of .hover().

$('li')
    .bind('mouseenter mouseleave', function(event) {
        $(this).toggleClass('test');
    });

Now lets use the new functionality of .hover() instead of manually binding the events.

$('li')
    .hover(function(event) {
        $(this).toggleClass('test');
    });

Sweet!

Sometimes though you’ll need to do more complex interactions than just toggling a class. In these cases you can simply check the event type that is passed to your handler. When the user mouses over, the event type sent to the hover function will be mouseenter. When the user mouses out, the event type sent to the hover function will be mouseleave. Here is an example checking the event type.

$('li')
    .hover(function(event) {
        $(this)[ (event.type == 'mouseenter') ? 'add' : 'remove') + 'Class' ]('test');
    });

In the above example I’m still just toggling the class on the element that was hovered over/out but doing so in a more verbose way to illustrate how you can check the event type.