Binding animation on many elements
I try to do some kind of grid that need to show dot based animation in the future. But it seams to perform pretty slowly even with a few elements (i need to开发者_C百科 apply it to maybe 5times that many items)
$('div').bind('shrink', function(){
var $that = $(this).find('> em > span');
$that.animate({'width': '3px', 'height': '3px'}, 500);
}).bind('grow', function(){
var $that = $(this).find('> em > span');
$that.delay(50).animate({'width': '100%', 'height': '100%'}, 300);
}).append('<em><span><span><em/>');
//triggering shrink and grow on hover
before starting to do complex animations i wanted to test it with a hover effect.
you can take a look at the demo here: http://jsfiddle.net/meo/GvfVb/7/
How could i improve the performance of this script?
I seem to get some performance improvements with this version:
Example: http://jsfiddle.net/patrick_dw/GvfVb/10/
var shrink = function() {
$(this).animate({
'width': '3px',
'height': '3px'
}, 500);
};
var grow = function() {
$(this.firstChild.firstChild)
.delay(50).animate({
'width': '20px',
'height': '20px'
}, 300);
};
$('div').append('<em><span><span><em/>')
.find('> em > span').mouseenter( shrink )
.end().mouseleave(grow)
.click(function() {
$(this).unbind('mouseleave', grow);
});
Here are the changes I made:
- Changed
shrink
andgrow
into named functions, so that.trigger()
doesn't need to be called to fire them, while retaining the ability to remove them by name. - Placed the
mouseenter
event directly on the<span>
tag so you don't need to do a.find()
every timemouseenter
fires. - The
mouseleave
needs to be on the<div>
so I optimized it by removing the.find()
and replacing it with a nativethis.firstChild.firstChild
. - This was probably the biggest performance improvement: I changed the
grow
function to animate thewidth
to an absolute value of20px
instead of100%
. Things really smoothed out with that change.
You could also probably unbind the mouseleave
when you click so that it isn't firing to no effect after the mouseenter
has been unbound.
精彩评论