Search code examples
jquerylivesettimeoutmouseenter

jQuery live function with setTimeout


I'm trying to combine mouseenter, live and setTimeout function to make some animations

$(".kundenList li").live("mouseenter", function(){
    if ($(this).children().length > 0) {
        $(this).data('timeout', setTimeout( function () {
            $(this).children("div.description").css({opacity: '0'});

            $(this).children("div.blacklayer").animate({
                opacity: '0.85'
            }, 300);

            $(this).children("div.description").animate({
                top: "-=200px",
                opacity: '1'
            }, 300).css( 'cursor', 'pointer' );

            $(this).addClass("activeLI");
        }, 300));
    }
});

Html looks like this

<ul class="kundenList">
    <li>
        <img src="t3.png" class="kundenImg" />
        <div class="blacklayer" style="opacity: 0;"></div>
        <div class="description">
            <h3>Title</h3>
            <p>Description</p>
        </div>
    </li>
</ul>

Since I'm posting the question scrip apparently doesn't work :) . Anyone know why? Thanks.

PS I need live function since I'm loading new content over ajax


Solution

  • this inside setTimeout is referring to the global window object. Store a reference to this in a temporary variable, as shown below. Fiddle: http://jsfiddle.net/de7Fg/

    $(".kundenList li").live("mouseenter", function(){
        var $this = $(this); //Reference to `$(this)`
    
        if ($this.children().length > 0) {
            $this.data('timeout', setTimeout( function () {
                // $this points to $(this), as defined previously
                $this.children("div.description").css({opacity: '0'});
    
                $this.children("div.blacklayer").animate({
                    opacity: '0.85'
                }, 300);
    
                $this.children("div.description").animate({
                    top: "-=200px",
                    opacity: '1'
                }, 300).css( 'cursor', 'pointer' );
    
                $this.addClass("activeLI");
            }, 300));
        }
    });