Skip to content
Advertisement

jQuery mouseout firing when injecting child element

I’m trying to create a function which will add an overlay to a thumbnail image when you hover over it and remove the overlay when you leave it. Here is my HTML…

<div class="thumb"><img src="i/testThumb.gif" /></div>

And here is my jQuery…

$('.thumb').live('mouseover', function(event){
    if($(this).find('.overlay').length == 0){
        $(this).prepend('<div class="overlay"></div>');
    }
    return false;
});
$('#galleryPanel .thumb').live('mouseout', function(event){
    $(this).find('.overlay').remove();
    return false;
});

The trouble is that when the overlay is created the mouse is already over it and that triggers the “mouseout” of the container, which removes the overlay, and it cycles continuously flashing on and off.

Is there an easy solution to this?

Advertisement

Answer

I you put one more div into the mix, I think you may find what you are looking for.

<style>
.hover { display:none;}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
$(document).ready(function(){

   $(".image").hover(
   function(over) {
     $(this).find(".hover").animate({opacity: "show", top: "55"}, "slow");
   },
   function(out) {
     $(this).find(".hover").animate({opacity: "hide", top: "55"}, "slow");
   });

}); 
</script>

<div class='image'>
    <div class='imageClass'>
        <img src='img1.jpg' />

        <div class='hover'>
            <img src='img1.jpg' />
        </div>

    </div>
</div>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement