While I know some jQuery to simplify front-end manipulation programming, I also aware of some of some “best practices” to level up the performance on browser, like caching through var and always descend from ID selectors. But I have doubts about this piece of code. Could it be done better?
Preamble: This code animates several blocks inside the (already cached) selector through .hover().
The HTML is something like this:
<div clas="block-link red">(...)</div>
<div clas="block-link yellow">(...)</div>
<div clas="block-link magenta">(...)</div>
<div clas="block-link moradopelusa">(...)</div>
And the jQuery to animate at hovering inside one of them:
var cached_blocks = jQuery(.block-link);
jQuery(cached_blocks).hover(function(){
var this_block = jQuery(this),
this_block_text = jQuery(this_block).children(div.text),
this_block_image = jQuery(this_block).children(div.image),
this_block_link = jQuery(this_block).children(div.link),
this_block_link_icon = jQuery(this_block_link).children(a.icon);
/* Animate in; show everything */
jQuery(this_block_text).animate(..);
jQuery(this_block_image).animate(..);
jQuery(this_block_link).animate(..);
jQuery(this_block_link_icon).animate(..);
}, function() {
var this_block = jQuery(this),
this_block_text = jQuery(this_block).children(div.text),
this_block_image = jQuery(this_block).children(div.image),
this_block_link = jQuery(this_block).children(div.link),
this_block_link_icon = jQuery(this_block_link).children(a.icon);
/* Animate out; put everything where they belong */
jQuery(this_block_text).animate(..);
jQuery(this_block_image).animate(..);
jQuery(this_block_link).animate(..);
jQuery(this_block_link_icon).animate(..);
});
I’m seeing that I am declaring variables again after hover, but I don’t know any technique to not doing again. Anyway, even that way it works like a charm.
Update: Fixed Code #1
var cached_blocks = jQuery(.block-link);
jQuery(cached_blocks).on('mouseenter mouseleave', function(){
var this_block = jQuery(this),
this_block_text = jQuery(this_block).children(div.text),
this_block_image = jQuery(this_block).children(div.image),
this_block_link = jQuery(this_block).children(div.link),
this_block_link_icon = jQuery(this_block_link).children(a.icon);
/* Animate in; show everything */
this_block_text.animate(e.eventType(...));
this_block_image.animate(e.eventType(...));
this_block_link.animate(e.eventType(...));
this_block_link_icon.animate(e.eventType(...));
});
Note 1: Yes, i’m using cached_blocks in other part of the code.
You seem to be repeating code for no good reason?
Unless you are using the variables containing the text/image/link… elements somewhere else aswell, caching them just to use with animate() on the next line is a waste of space.