4

I am learning about javascript and css3 games and I am working on an alien game. The game is a guessing game where you enter a guess of X and Y position and the missile moves towards the alien using css3 transition. When the missle reaches the alien the explosion is supposed to appear; but I am having difficulty detecting when the transition is over. Currently the explosion appears right when you make the X and Y guess and the missle takes off. How can I detect with Javascript when the css3 transition is over to make the explosion appear?

Here is what I currently have:

the stylesheet:

#explosion
{
  width: 20px;
  height: 20px;
  position: absolute;
  display: none;
  background-image: url(../images/explosion.jpg);
}

#alien
{
  width: 20px;
  height: 20px;
  position: absolute;
  top: 20px;
  left: 80px;
  background-image: url(../images/alien.jpg);
}

#missile
{
  width: 10px;
  height: 10px;
  position: absolute;
  top: 240px;
  left: 145px;
  background-image: url(../images/missile.jpg);
  /*Transition*/
  -webkit-transition: all 0.5s ease-out 0s;
  -moz-transition: all 0.5s ease-out 0s;
  transition: all 0.5s ease-out 0s;
}

And the Javascript:

if(guessX >= alienX && guessX <= alienX + 20)
{
  //Yes, it's within the X range, so now let's
  //check the Y range
  if(guessY >= alienY && guessY <= alienY + 20)
  {
    //It's in both the X and Y range, so it's a hit!
    gameWon = true;
//move missle towards alien

//make explosion appear
explosion.style.top = alienY + "px";
explosion.style.left = alienX + "px";
explosion.style.display = "block";

  endGame();
 }
}
Ramona Soderlind
  • 203
  • 2
  • 13
  • possible duplicate of [CSS3 transition events](http://stackoverflow.com/questions/2794148/css3-transition-events) – Felix Kling Apr 23 '13 at 19:32

3 Answers3

7

I use the following, found here: https://stackoverflow.com/a/13862291/2312574

$('div').on('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', function() { 
    // do something
});
Community
  • 1
  • 1
mikedidthis
  • 4,899
  • 3
  • 28
  • 43
6

Use transitionend event to detect when transition is finished.

Marat Tanalin
  • 13,927
  • 1
  • 36
  • 52
4

The transitionend event.

Documentation: http://www.w3.org/TR/css3-transitions/#transition-events

Demo: http://jsfiddle.net/c937L/

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405