Why in the following code I can not click the button programmatically to translate the div
again ?
const div1 = document.getElementsByClassName("div1")[0];
div1.addEventListener("transitionend", callback);
// Why this one does not work?
// div1.addEventListener("transitionend", play);
function play() {
div1.classList.add("play");
}
function callback() {
div1.classList.remove("play");
// or this one?
// play();
}
.div1 {
width: 200px;
height: 100px;
background-color: limegreen;
}
.play {
transition: transform 1s;
transform: translateX(100px);
}
<div class="div1"></div>
<button onclick="play()">Play</button>
3
Answers
When you click the "Play" button, the
play
function is called and it adds the "play
" class todiv1
. This triggers a transition and when the transition ends, the callback function is called, which removes the "play
" class.If you want to toggle the translation on/off with button click modify the
play
function to add or remove the "play
" class based on whether it’s thereYou should stop the animation with removing the
play
class and start it again with adding theplay
class after a zero timeout (that allows the browser to re-render and start the animation fresh):there is no effect to changing the class instantly.
that is why you should use
setTimeOut
to callplay
againyou might also use css animation to get the same effect with cleaner code