Jerph
Jerph

Reputation: 4580

Set one CSS property to the value of another in JQuery?

For example, to animate a box from the left, I can set "left" to the negative value of "width", and animate it to zero:

 $('.box').each(function(){
      $(this)
           .css('left', $(this).width()*-1 )
           .animate({'left':0},1000)
           ;
 });

Is there a way to do this without the each function? THIS JQUERY IS TOO VERBOSE!

Upvotes: 0

Views: 599

Answers (2)

mishac
mishac

Reputation: 3314

I'm not sure why you needed to add the "each" in the first place, because most jQuery functions work on multiple elements simultaneously. This should work:

 $('.box').css('left', $(this).width()*-1 ).animate({'left':0},1000);

EDIT: code doesn't work as mentioned in the comments, because $(this) doesn't refer to the right object. This should fix it:

 var $box = $box.css('left', $box.width()*-1 ).animate({'left':0},1000);

Upvotes: 1

Ali
Ali

Reputation: 267317

Put the function in its own function called animateBox(). Then you can do this:

$('.box').each(animateBox);

Upvotes: 0

Related Questions