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/.

comments powered by Disqus

4 Comments

  • 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.

  • 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.

  • Thanks for the tip!!

    Aloha,

    Kevin

  • Great tip. Thanks!!!

Comments have been disabled for this content.