views:

31

answers:

3

How can I simplify my jQuery animation? What is the best way?

Code:

$("#nav").animate({opacity:0.2},1000);
$("#sub_nav").animate({opacity:0.2},1000);
$("#user_links").animate({opacity:0.2},1000);
$("#logo").animate({opacity:0.2},1000);
$(".top_buttons").animate({opacity:0.2},1000);
$(".pageheaders").animate({opacity:0.2},1000);
$(".heading_sub_text").animate({opacity:0.2},1000);
$("#copyright").animate({opacity:0.2},1000);
$("#footer_links").animate({opacity:0.2},1000);
+2  A: 

Either give each of the elements a class (or an additional class):

$('.someNewClass').animate({opacity:0.2},1000);

Or place all your elements in one selector, separated by commas.

$("#nav,#sub_nav,#user_links,#logo,.top_buttons,.pageheaders,.heading_sub_text,#copyright,#footer_links").animate({opacity:0.2},1000);

Or a combination of the two, adding a class just the ones that don't currently have a class.

// These get .someNewClass: #nav,#sub_nav,#user_links,#logo,#copyright,#footer_links
$(".someNewClass,.top_buttons,.pageheaders,.heading_sub_text").animate({opacity:0.2},1000);
patrick dw
+1, you could also use `fadeTo` in this case.
Matt
A: 

Since it appears that your are animating a group of elements, could you possibly wrap all of them in a div and then just animate that div?

Depending upon your needs, you may also want to look at jQuery Tools' Expose functionality. It basically dims the background and highlights (or exposes) a particular object. The also have an overlay tool if that's more like what you are attempting to accomplish.

Topher Fangio
A: 

What patrick dw suggests will clean up your jQuery code substantially. Of his suggestions, I consider the first one the best. However, I will make a point that it is far more important to emphasize selector/effect optimization (over cosmetic improvements).

However, consider the following code.

var c = $('<div class="container" />').appendTo($('body'))
for(var i = 0; i < 1000; i++) {
  c.append($('<div />')
   .css('height', 30)
   .css('width', 30)
   .css('borderWidth', 2)
   .css('borderStyle', 'solid')
   .addClass('anim'))
}

This creates div.container and puts 1000 copies of div.anim inside it. Do this, then compare the performance of $('.container').fadeOut() versus $('.anim').fadeOut(). Animating a containing div is orders of magnitude faster than animating its many children. If possible, always animate out a wrapper if you want to animate all of its children in an identical fashion.

Steven Xu