Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to animate two things at the same time in jquery

I want to animate 2 things at same time when mouse hovers something.

for example I want to change background color of box1 with id = "box1" and position of box2 with id="box2" when mouse hovers a div with id="trigger".

but I don't want them to animate in a queue, i.e. one after another. I want them to start animating at same time and finish at same time!

like image 623
Mehran Avatar asked Sep 04 '10 13:09

Mehran


2 Answers

While it's true that consecutive calls to animate will give the appearance they are running at the same time, the underlying truth is they're distinct animations running very close to parallel.

To insure the animations are indeed running at the same time use:

$('#trigger').hover(function() {
    $('#box1').animate({..., queue: 'trigger-hover'});
    $('#box2').animate({..., queue: 'trigger-hover'}).dequeue('trigger-hover');
});

Further animations can be added to the 'trigger-hover' queue and all can be initiated provided the last animation dequeue's them.

Cheers, Anthony

like image 135
Borgboy Avatar answered Oct 01 '22 19:10

Borgboy


You can just run them in a row, like this:

$("#trigger").hover(function() {
   $("#box1").stop().animate({ backgroundColor: '#000000' });
   $("#box2").stop().animate({ top: "-20px" });
}, function() {
   $("#box1").stop().animate({ backgroundColor: '#FFFFFF' }); //set it back
   $("#box2").stop().animate({ top: "0px" });                 //set it back
});

This uses .hover() to animate one way when hovering, and animate them back when leaving. The .stop() is just to prevent animation queue build-up. To animate a color, you'll need either the color plugin, or jQuery UI included as well.

Animations in jquery, .animate(), are implemented using setInterval() with a 13ms timer, so they'll happen outside the normal flow...doing them like above doesn't wait for the first to finish, they'll run simultaneously.

like image 22
Nick Craver Avatar answered Oct 01 '22 19:10

Nick Craver