Meules
Meules

Reputation: 1389

Dynamic content mouse over and out

I have some divs that are created with data from a json string. Most of them are images. Over those dynamic loaded images and want to show a div when mouse over it and hide when you mouse out. Therefore I used the live function, found it here on the forum. The mouse over function works but it won't mouse out. So when I hover one image the div shows up but when I mouse out the div is still visible. Any suggestions on this?

My code

<script type="text/javascript">
    $('.product').live("hover", function() {
        $(this).find('.product').stop(false,true); // get the image where hovering
        $(this).find('div.caption').stop(false,true).fadeIn(100); // and fade in
    },
     function() {
        $(this).find('.product').stop(false,true); // on mouse leave hide it  
        $(this).find('div.caption').stop(false,true).fadeOut(100); // fade out
     });
</script>

UPDATED ANSWER Thanks to the help below I found the solution.

$(".productsGrid .product").live("mouseenter", function() {$(this).find('.product').stop(false,true);
$(this).find('div.caption').stop(false,true).fadeIn(100);})
$(".productsGrid .product").live("mouseleave", function() { $(this).find('.product').stop(false,true);   
$(this).find('div.caption').stop(false,true).fadeOut(100);});

Upvotes: 0

Views: 1573

Answers (1)

James Montagne
James Montagne

Reputation: 78640

The issue is that live only takes one function parameter, not 2 in the way that the hover function does. Using hover with live basically just binds the one function to both mouseenter and mouseleave.

You can see an explanation and solution here.

However, unless you are using a version of jquery prior to 1.7, you should not be using live as it is deprecated. You should instead use on.

Your code would look something like this:

$(STATIC ANCESTOR).on({ 
        mouseenter: 
           function() 
           { 

           }, 
        mouseleave: 
           function() 
           { 

           } 
       }, ".product"
    ); 

Where STATIC ANCESTOR is replaced with an ancestor element of your .product elements which is not dynamically loaded. If needed document can be used but should only be used as a last resort.

Upvotes: 2

Related Questions