Dmitrii Mikhailov
Dmitrii Mikhailov

Reputation: 5221

Background image won't change

I want to change div's background image inside setInvterval, but can't figure out how. Here's the code:

$('.thumbnail').on({
        'mouseenter': function(){
            var thumbs = $(this).attr('data-num-thumbs');
            var thumb_url = $(this).css('background-image');
            console.log(thumb_url);
            var i = 1;
            setInterval(function(){
                var new_thumb_url = thumb_url.replace(/\d{1,2}\.jpg/gi, i + '.jpg');
                console.log(new_thumb_url);
                $(this).css('background-image', new_thumb_url);
                i++;
                if(i > 10) i = 1;
            }, 3000);
        });
});

This is how div looks like:

<div data-num-thumbs="17" class="thumbnail" style="background: url('http://site/img/11.jpg') no-repeat;"></div>

Upvotes: 0

Views: 321

Answers (1)

dreamweiver
dreamweiver

Reputation: 6002

It looks like $(this) inside setInterval() is mapping to something else , try this

$('.thumbnail').on({
    'mouseenter': function(){
        $this=$(this);  //store $(this) in a local var
        var thumbs = $(this).attr('data-num-thumbs');
        var thumb_url = $(this).css('background-image');
        console.log(thumb_url);
        var i = 1;
        setInterval(function(){
            var new_thumb_url = thumb_url.replace(/\d{1,2}\.jpg/gi, i + '.jpg');
            console.log(new_thumb_url);
            //$(this).css('background-image', new_thumb_url);
            $this.css('background-image', new_thumb_url);
            i++;
            if(i > 10) i = 1;
        }, 3000);
    }
});

Happy Coding:)

Upvotes: 1

Related Questions