I need to animate a sprite on hover and thats it! I tried some plugins but decided to write my own. Here it is:
(function($) {
function animate(opts, t) {
if (opts.bgpos === opts.width * opts.frames) {
t.css('background-position-x', '0px');
} else {
opts.bgpos = opts.bgpos + opts.width;
t.css('background-position-x', opts.bgpos + 'px');
}
}
$.fn.spin = function(options) {
var t = $(this);
var opts = $.extend({}, $.fn.spin.defaults, options);
var frames = t.data('frames');
var bgpos = parseInt(t.css('background-position-x'),10);
opts = $.extend({
'frames': frames,
'bgpos': bgpos
}, opts);
setInterval(animate(opts, t), 1000 / opts.fps);
};
$.fn.spin.defaults = {
fps: 7,
width: 236
};
})(jQuery);
[It’s called spin because the sprite animation is of a spin]
I’m calling it like this:
$('article.post').on({
mouseenter: function() {
var t = $(this);
t.children('div.filmstrip').spin();
}
});
However the animation only moves one frame per hover. From what I’ve found this is because I am using function call not reference in my setInterval. I can make the setInterval loop if I remove the () however my animate function fails without its variables.
How do I get my $(this) & options into my animate function with setInterval? Or?
window.setInterval()requires a parameter of typefunction, but you supply the return value ofanimate, which isundefined.When you write
you are telling the JS engine to execute
animate(opts, t)immediately, and then callsetIntervalon the returned value, which in this case isundefined, since your function doesn’t explicitely returns anything. So is like the following happened:Thus you are not scheduling anything. You may want to use a function literal
so that the closure
is passed to
setIntervaland is scheduled for later execution.