Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Animate a slide on two divs and have them return to their original position

I have two divs. one is off the page on the left by -50% the other is in the center of the page at 50%. when a button is clicked I add 100% to both divs with an animation so that they slide to the right. At that point the first div is now on the page at 50% and the second is off to the right at 150%.

In order to be able to continue sliding the divs to the right, I wrote a call back to subtract 100% from the divs to return the first one to -50% and the second one to 50%.

The problem is that for some reason after the callback both divs are set to "left: -50%".

Here is my code $(".Ssave").click(function () { $(".scanner_width").animate({ left: '+=100%' }, function () { $(".scanner_width").css("left", "-=100%"); }); });

1 Answer

Steven Parker
Steven Parker
243,656 Points

This is a tricky one!

You didn't show your HTML, but I'm guessing you have two elements that both have the class "scanner_width". So your selector for the animate targets them both, and they both begin animating. When the first one finishes, your complete function runs. Then you use the same selector to adjust the left attributes of both elements. But the second one is still being animated!

So the next (and probably the last) animation step of the second element immediately puts it back where it was and when it finishes, the same completion function runs. Since the animation had restored the second object, it gets moved back just once. But the first element gets moved back a second time.

So the final positions depend on which one finishes first. If the one starting at -50 finishes first, the final positions will be -150 and 50. But if the one starting at 50 finishes first (which is apparently your case), the final positions will both be -50.

Now that's only for the first button click. If you keep clicking the button, the early finisher will keep being pushed back further and further each time.

thanx, I went it over step by step until I got it to work in order.