Sunday, April 3, 2011

jQuery hover() not working with absolutely positioned elements and animation...

I have some html that looks like this:

<a href="#" class="move"><span class="text">add</span><span class="icon-arrow"></span></a>

And I have a jquery event registered on the anchor tag:

$('a.move').hover(
    function (event) {
        $(this).children('span.text').toggle();
        $(this).animate({right: '5px'}, 'fast');
    },
    function (event) {
        $(this).children('span.text').toggle();
        $(this).animate({right: '0px'}, 'fast');
    }
);

When I mouse over the anchor tag, it displays the span.text and moves the anchor 5px to the right.

Now, due to complications that I don't feel like getting into, I have to set position: relative; on the container and absolutely position the icon and the text so that the icon appears on the left and the text on the right.

THE PROBLEM:

When I mouse over the anchor tag, the icon moves right, and the mouse ends up over top of the text (which appears). Unfortunately, the 'out' function gets called if I move my mouse from the icon to the text and the animation starts looping like crazy. I don't understand what's causing the "out" event to fire, as the mouse is never leaving the anchor tag.

Thanks!

From stackoverflow
  • Instead of hover you can use the "mouseenter" and "mouseleave" events, which do not fire when child elements get in the way:

    $('a.move').bind('mouseenter', function (e) {
      $(this).children('span.text').toggle();
      $(this).animate({right: '5px'}, 'fast');
    })
    .bind('mouseleave', function (e) {
      $(this).children('span.text').toggle();
      $(this).animate({right: '0px'}, 'fast');
    });
    
    Erik van Brakel : Aaah, thanks. Solution to my problem at least ;-) +1!

0 comments:

Post a Comment