views:

452

answers:

1

Hi

I've got this markup (simplified):

<div class='item'>
  <a> one link </a>
  <a class='trash'><img src='trash.png'/></a>
</div>

I'm highlighting the div when the mouse enters, and showing the (otherwise hidden) 'trash' link (it's like a tiny trash bin) so the user can delete the link.

I can't use 'hover' effect, because I need them to be live events. So I'm doing mouseover and mouseout. This is the code:

$('div.link').live('mouseout', function(e){
     console.log(e)
     if(e.target == this){
      $(this).removeClass('hover');
      $(this).children('a.trash').fadeOut();
     }
    });

(mouse over does the exacto opposite).

The animation looks quirky though, what am I doing wrong?

Thanks so much!

+2  A: 

The mouseover and mouseout events are also fired when the mouse enters and leaves any child elements. Try using the mouseenter and mouseleave events instead.

Unfortunately, the live method doesn't currently support these methods. You'll have to bind them manually when you add/remove links.

function toggleDelete() {
      $(this)[($(this).hasClass('hover') ? 'remove' : 'add') + 'Class']('hover');
      $(this).find('a.trash').toggle();
}

$('div.link').bind('mouseenter, mouseleave', toggleDelete);

$('.add').click(function(e) {
    var link = $('<a />').addClass('link');
    link.bind('mouseenter, mouseleave', toggleDelete);
    $('.parent').append(link);
});
bendewey