Simply i have a div which should be animated when i click on a button and hidden when i click on another button:
<div id="popup"></div>
<input type="button" value="show and animate popup" onClick="showWithAnimation()" />
<input type="button" value="hide" onClick="aFunction()" />
<script>
function showWithAnimation(){
console.log('animation called');
$('#popup') .animate({top:(($(window).height()/2)-($('#popup').outerHeight()/2))-70}, 1000, 'easeOutBounce');
$('#popup').show();
}
function aFunction(){//Hide the div
$('#popup').hide();
}
</script>
What i noticed, is that the bounce effect is applied on the div only for the first time i click on the show and animate popup, then when i click on hide button and then re-click again on show and animate popup button, the div is shown, but without easeOutBounce effect. may i ask you how to go to solve that? Thanx in advance.
I think this is happening because when the animation is run, the div is in a certain position on the page…but when you rerun it, the div is already in the target position…so it looks like no animation/effect is happening. It’s happening, it’s just already where you’re trying to animate it to. You need first set the
topandleftstyles to specific values…maybe the top middle of the window. Then, you callanimatelike you are. This way, whenever you click to show the popup, the popup’s position always starts at the same place, and animates/ends at the same place.So you would need:
UPDATE:
When you use
animate, it literally animates the selected element(s) from its original values to have the properties you pass it. So in your case, you are animating thetopandleftstyles. By default, the div is positioned somewhere on the page – I think with yours, it’s hidden and just somewhere in the middle of your HTML. So technically, it’stopandleftare undefined, but are really some finite values, like “200, 250”. When you call animate, it gradually changes these from the original (200, 250) to what you specify in theanimatecall. So, after the FIRSTanimatecall, you move (animate) the div to the center of the window. Then you allow the popup to be closed (hidden). Every click to open the popup after that, it attempts to move (animate) the div to the center of the window…but it’s already there (just hidden). So there “isn’t” an animation because it’s trying to move the div to the position it’s already in. Again, as you’ve noticed in your testing, it’s important to note that this happens only after the first time because the div has already been moved to its target position. If you opened the popup, closed it, resized the window, and then opened the popup again, I’m sure there would be some kind of animation (minimally probably). This is because the dynamic target position of the div you specify in theanimatecall has changed (since the window has resized).