views:

33

answers:

3

I have a list of thumbnails. When I click on a thumbnail, I want the image to load after half a second. Here's my code:

$('ul#thumbs li img').click(function() {

    setTimeout(function() {
        $('img#image').attr("src", $(this).attr("src").replace("_thumb", ""));
    }, 500);

});

When I click on one of the thumbs, nothing happens. If I remove the setTimeout function, and just have the image load immediately, it works fine.

Anybody know why the event wouldn't fire?

A: 

The setTimeout function will change the function context (the this value) inside the callback, it will point to the global object, you need to store the this value outside, in the click event handler:

$('ul#thumbs li img').click(function() {
    var that = this;
    setTimeout(function() {
        $('img#image').attr("src", $(that).attr("src").replace("_thumb", ""));
    }, 500);
});

See also:

CMS
A: 

this isn't what you think it is. When you use setTimeout, this is no longer a reference to the current element when the function gets executed.

You'll need to make sure you are keeping track of the proper element, like so:

$('ul#thumbs li img').click(function() {
    var thumbImg = this;
    setTimeout(function() {
        $('img#image').attr("src", $(thumbImg).attr("src").replace("_thumb", ""));
    }, 500);

});
TM
Interesting, I didn't know that. Thanks!
Steven
A: 

The problem is the scope of this in the timeout function try this:

$('ul#thumbs li img').click(function() {
    var self = $(this);
    setTimeout(function() {
        $('img#image').attr("src", self.attr("src").replace("_thumb", ""));
    }, 500);

});

Or even better this:

$('ul#thumbs li img').click(function() {
    var src = $(this).attr("src").replace("_thumb", "");
    setTimeout(function() {
        $('img#image').attr("src", src);
    }, 500);

});
PetersenDidIt
note: the 2nd example might not work if the `src` attribute could change within the timeout period. if it is static, it will work fine though.
TM