jonhobbs
jonhobbs

Reputation: 27982

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?

Upvotes: 1

Views: 2409

Answers (3)

gradbot
gradbot

Reputation: 13862

Instead of binding mouseout to ".thumb" trying binding it to ".overlay".

$('#galleryPanel .overlay').live('mouseout', function(event){
    $(this).remove();
    return false;
});

Upvotes: 1

superUntitled
superUntitled

Reputation: 22567

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>

Upvotes: 1

Rich
Rich

Reputation: 36856

This might sound a little hacky, but you can use a variable (in the case of a dom element, I'd use a css class) to know if this is the first time the event is firing on this element.

Basically, your function looks for the presence of this css class on the dom element, but it's not there by default when you create it. If it's not there, add the class and exit the function. If it is there, the hit is valid and you should execute your overlay functionality. Since you can have multiple classes on a dom element, this shouldn't cause any conflict with any other classes used for styling. I'd say go with a class instead of a custom attribute because custom attributes make your html "invalid" to search crawlers.

Upvotes: 0

Related Questions