Handling MouseEnter and MouseLeave Events in jQuery

I have a simple table generated by an ASP.NET MVC view and needed to switch out CSS classes as the user hovered over rows.  Initially I used the rather obvious “hover” feature built-into jQuery since it provides a way to write code that’s called as the user enters and leaves an object.  I ended up doing something like this:

$(this).closest('tr').hover(
    function()
    {
        $(this).addClass('Over');
    },
    function()
    {
        $(this).removeClass('Over');
});


While this works, I was looking into another scenario today and realized that it’s much easier to do the toggle effect using the jQuery bind() function combined with toggleClass().  Either way works, but I’m all for less code where possible.  Here’s how to achieve the same “hover” effect with less code:

$(this).closest('tr').bind("mouseenter mouseleave", function(e)
{
    $(this).toggleClass("Over");
});


The toggleClass() function automatically handles adding and removing the Over CSS class and the bind() function handles attaching to the mouseenter and mouseleave events.  Nice and clean…

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit http://www.thewahlingroup.com/.

Published Monday, April 13, 2009 5:54 PM by dwahlin
Filed under: , ,

Comments

# re: Handling MouseEnter and MouseLeave Events in jQuery

Monday, April 13, 2009 9:07 PM by Rick Strahl

Keep in mind that .hover is a high level abstraction and does a lot more than just handle mouseenter and mouseleave and this may or may not matter in your scenario. Specifically building hover behavior is often tricky because mouseenter/leave fire when entering child elements. .hover() accounts for that and only fires its events when you enter and leave the actual container you're attaching the events to, which is usually the behavior you want.

# re: Handling MouseEnter and MouseLeave Events in jQuery

Monday, April 13, 2009 9:53 PM by dwahlin

Thanks Rick.  I don't have to worry about that in this situation (not yet anyway) but that's definitely something to keep in mind as more controls are added that may be hovered over.

# re: Handling MouseEnter and MouseLeave Events in jQuery

Tuesday, April 14, 2009 1:20 PM by kdavis6

Thanks for the tip!!

Aloha,

Kevin

# re: Handling MouseEnter and MouseLeave Events in jQuery

Wednesday, April 22, 2009 11:08 PM by habib

Great tip. Thanks!!!