Pregunta

I have a HTML code like this on my page :

<li><img width="100" alt="3Caballeros.png" onmouseover="show_buttons();"</img></li>

Basically a couple buttons should show up when the user hovers the image. The *show_buttons()* method should set this up. Here it is :

function show_buttons(item){
var parent =$('img[alt="'+item.alt+'"]').parent();
alert(parent.prop('tagName'));    //says LI
parent.find('img').fadeIn();      //shows the other images in the LI (they are added by JavaScript)
item.onmouseover =function () {};   //removes the event listener to the image
parent.mouseout( parent, function(){
    parent.find('img[alt!="'+item.alt+'"]').fadeOut();
});
parent.mouseover( parent, function(){
    parent.find('img[alt!="'+item.alt+'"]').fadeIn();
});

}

The images are added with the prepend() method, and the result is something like :

 <li><img class="first_button" src="images/first.png" style="display: none;">
 <img class="second_button" src="images/second.png" style="display: none;">
 <img width="100" alt="3Caballeros.png" onmouseover="show_buttons();"</img></li>

So the code is almost fine : the images are shown when the cursor enters the LI and disappear when it leaves. The problem is, when the cursor hovers one of the images added dynamically in the LI the mouseover event is triggered, so the image disappears. These images are in the LI, so why is the event triggered?

How can I solve this? Thanks

¿Fue útil?

Solución

I don't know your exact set-up (no CSS etc), but the following changes should probably do the trick:

// Replace 'parent.mouseout(...' with:
parent.mouseleave(...

// Replace 'parent.mouseover(...' with:
parent.mouseenter(...

See, also, this SHORT DEMO.

The (possible) cause of the problem
Quoting jQuery's docs regarding .mouseover():
"This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves over the Inner element in this example, a mouseover event will be sent to that, then trickle up to Outer. This can trigger our bound mouseover handler at inopportune times.

In your case, when moving from one image to the next a mouseout event was generated on the image and then bubbled up to the containing li, causing that unexpected behaviour. Using .mouseenter() and .mouseleave() iseems to be a better alternative !

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top