Dmitrii Mikhailov
Dmitrii Mikhailov

Reputation: 5231

Cannot use 'in' operator to search for 'backgroundPositionX' in undefined

Can't figure out why this thing happens.

var thumb_width = 240;
var thumb_height = 180;
$('.video-thumbnail').on({
        'mouseenter': function(){
            var i = 0; var j = 0;
            $(this).id = setInterval(function(){
                $(this).animate({
                    'background-position-x': -(j * thumb_width),
                    'background-position-y': -(i * thumb_height)
                });
                i++; j++;
            }, 1000);
        }
    })
});

Upvotes: 1

Views: 1299

Answers (2)

Radko Dinev
Radko Dinev

Reputation: 887

You are assuming a wrong context in the setInterval's callback, as setInterval is bound to the global object (window).

Also the background-position-x and background-position-y aren't part of any CSS specification and you cannot set them apart (read more in that answer).

Try this:

...
var $this = $(this);
$this.id = setInterval(function() {
  var xPos = -(j * thumb_width);
  var yPos = -(i * thumb_height);
  $this.animate('background-position', xPos + 'px ' + yPos + 'px');
  ++i;
  ++j;
}, 1000);
...

Upvotes: 0

dfsq
dfsq

Reputation: 193271

Because setInterval runs in Window context. In order to fix it you should explicitly provide proper object context. You have couple of options:

Using $.proxy:

$('.video-thumbnail').on({
    'mouseenter': function() {
        var i = 0; var j = 0;
        $(this).id = setInterval($.proxy(function() {
            $(this).animate({
                'background-position-x': -(j * thumb_width),
                'background-position-y': -(i * thumb_height)
            });
            i++; j++;
        }, this), 1000);
    }
});

Or using reference to this:

$('.video-thumbnail').on({
    'mouseenter': function() {
        var i = 0; var j = 0, self = this;
        $(this).id = setInterval(function() {
            $(self).animate({
                'background-position-x': -(j * thumb_width),
                'background-position-y': -(i * thumb_height)
            });
            i++; j++;
        }, 1000);
    }
});

Upvotes: 1

Related Questions