I am trying to do the following with CSS translate:
When a button is clicked, balloons appear and fly away. When they finished flying, they disappear and return to the starting position (so that when the next time a button is clicked the same behavior happens).
Up till now I got the following (balloon is only flying up and does not appear / disappear).
HTML
<div>
<img class="object" src="http://pngimg.com/upload/balloon_PNG580.png" />
</div>
<br><br><button id="button">Fly!!!</button>
CSS
div{
height: 300px;
position: relative;
}
.object {
width: 60px;
position: absolute;
bottom: 0;
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
}
.move-up{
transform: translate(0,-150px);
-webkit-transform: translate(0,-150px);
-o-transform: translate(0,-150px);
-moz-transform: translate(0,-150px);
}
JS
$('#button').click(function(){
$('.object').addClass('move-up');
});
The problem is that when I try it to appear with adding starting display : none
to object and on click add $('.object').show()
my animation does not start at all. How to may my balloon fly?
You can achieve this effect using CSS3 animations. Please refer inline comments for more details on each item.
CSS:
.object {
width: 60px;
position: absolute;
bottom: 0;
opacity: 0; /* make the balloon invisible on load and once animation is complete */
}
.move-up{
-webkit-animation: balloon 1s linear; /* the animation to move up */
-moz-animation: balloon 1s linear;
animation: balloon 1s linear;
}
@keyframes balloon { /* included only unprefixed version to keep answer short, demo has the prefixed versions also */
5% {
transform: translate(0, 0); /* keep at original position */
opacity: 1; /* make opacity as 1 after a short time for balloon to appear */
}
50% {
transform: translate(0, -150px); /* move up */
opacity: 1; /* retain the opacity */
}
55%, 100% {
transform: translate(0, -150px); /* retain translated position till end */
opacity: 0; /* hide the ballons and make it hidden for the rest of the duration */
}
}
jQuery:
$('#button').click(function(){
$('.object').addClass('move-up'); // adding the move up animation class to make it move
$('.object.move-up').on('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd',function(){
$('.object').removeClass('move-up'); // removing the animation class on animation end to make it come back to original state
});
});