Search code examples
jqueryjquery-selectorsthis

$(this) child element css change not working at all


I have a little question.

 $('.item').mouseenter(function() {
    setTimeout(function() {
  $(this).find('.item-overlay').css('z-index', '-1');
}, 300);
}).mouseleave(function() {
  $(this).find('.item-overlay').css('z-index', '');
});

 <div class="item">
    <div class="item-overlay">
    </div>

    <iframe>...</iframe>

 </div>

Everything works fine, except one small thing. z-index isn't changing. Can you guys help me out with this? I've also tried with "next", "child", "find" - none worked :(


Solution

  • this within the function you're passing setTimeout will be window, not the element. (this depends on how a function is called, not where it's used.)

    You can save the this value the event handler got (or actually, as you're going to jQuery-wrap it, just do that with a var outside the setTimeout function), e.g.:

    $('.item').mouseenter(function() {
        var $this = $(this);
        setTimeout(function() {
            $this.find('.item-overlay').css('z-index', '-1');
        }, 300);
        // ...