I have some experimental script, that makes animation of ul list element background-position, when list element is hovered. Is there another way to manage this task ? or just optimize this code ?
-
The best optimization I can think of is using CSS animations, which in some browsers use hardware acceleration. Do you mind if it doesn't work in all browsers?user142019– user1420192011-06-27 19:06:42 +00:00Commented Jun 27, 2011 at 19:06
-
8For better results, consider posting this here: codereview.stackexchange.comJames Allardice– James Allardice2011-06-27 19:07:33 +00:00Commented Jun 27, 2011 at 19:07
-
I'll check CSS animation... but yes I'm with cross browser compatibility :)wolf3d– wolf3d2011-06-27 19:11:33 +00:00Commented Jun 27, 2011 at 19:11
-
thank You for this recommendationwolf3d– wolf3d2011-06-27 19:12:32 +00:00Commented Jun 27, 2011 at 19:12
4 Answers
var c = 0,
ids;
$(function(){
$("li.animate").hover(function () {
ids = setInterval(function() {
$('.animate').css('backgroundPosition', ((++c==4) && (c=0), (-100 * c) + 'px 0'));
}, 40);
}, function () {
$('.animate').css('backgroundPosition', '0 0');
clearInterval(ids);
}
);
});
1 Comment
var c = 0;
var ids;
$(document).ready(function(){
$("li.animate").hover(
function () {
var param = '0 0';
ids = setInterval(function() {
if ( c > 4 ) {
c = 1;
param = '0 0';
}
else {
param = (-100 * c++ ) + 'px 0';
//alert(param);
}
$('.animate').css('backgroundPosition', param);
//$('#foo').fadeOut();
}, 40);
},
function () {
$('.animate').css('backgroundPosition', '0 0');
clearInterval(ids);
}
);
});
As the basic optimization code, I could only reposition the jQuery statement where the "css()" method is called in the first function section.
Hope it helps.
Comments
The best way to optimize a 40 millisecond timer interval is to not call expensive jQuery functions within it. Store the call to $('.animate') in a variable outside the interval function, then loop through it with for like a normal array, and use standard DOM properties to change the styles of each element. That's the gist of it, I added in some code reorganization to make things a bit simpler as well.
var c = 0, ids;
$(document).ready(function(){
$("li.animate").hover(function () {
var ani = $('.animate'), l = ani.length;
ids = setInterval(function() {
var i, param;
if ( c >= 5 ) {
c = 1;
param = '0 0';
} else {
param = (-100 * c++) + 'px 0';
}
for (i=0; i<l; i++) {
ani[i].style.backgroundPosition = param;
}
}, 40);
},
function () {
$('.animate').css('backgroundPosition', '0 0');
clearInterval(ids);
}
);});
Try it: http://jsfiddle.net/nDgSE/4/