0

I usually manage to make (this) work in JQuery, but in this specific case it simply doesn't work.

I've got a list of articles, with each article having a div with photos. But in case an article has many photos that can't fit in the div's regular height (430px), the div that holds the photos inside an article div should have overflow scroll. The css manipulation to make overflow scroll is delayed with setTimeout. However, if I don't use the this selector, all articles get overflow scroll when I only hover one of them. To give this effect only to the specific div that I hover I have to use the this selector, but when I do that, nothing happens.

Here's my code:

$(document).ready(function() {
    $(".scrapPhotosThree").mouseover(function() {
        setTimeout(function () {
            $(this).css( "overflow", "scroll" );
        }, 1000);
    });

    $(".scrapPhotosThree").mouseout(function() {
        setTimeout(function () {
            $(this).css( "overflow", "hidden" );
        }, 1000);
    });
});

When I replace $(this).css... with $(".scrapPhotosThree").css..., the effect appears that all articles change when I only hover one.

Who knows how I can fix this?

user2793161
  • 79
  • 1
  • 2
  • 13

2 Answers2

2

Inside the function called by setTimeout(), this will be the global object, not the element you were working with.

You can either cache this in a local variable (sometimes named that or self) and use that variable in the delayed function, or you can bind the delayed function to the current this with $.proxy():

$(".scrapPhotosThree").mouseover(function() {
    setTimeout($.proxy(function() {
        $(this).css("overflow", "scroll");
    }, this), 1000);
});

Note that recent versions of Javascript expose a Function.bind() method that offers the same functionality as $.proxy().

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
1

I'm not 100% sure, but i would try something like this:

$(document).ready(function() {
    $(".scrapPhotosThree").mouseover(function() {
        var _this = $(this);
        setTimeout(function () {
            $(_this).css( "overflow", "scroll" );
        }, 1000);
    });

When you put the setTimeout in between, it's not "in" the .mouseover anymore, so you get a different element i believe.

Davy
  • 691
  • 1
  • 7
  • 18