I need to change the width and height of an element using js with a smooth transition. My idea was to add a class to the element which makes the transition smooth, change the width and height, and once the transition is done, removing the class again. I use the following code:
element.classList.add("smoothTransition") element.classList.toggle("fullscreen") element.addEventListener("webkitAnimationEnd", element.classList.remove("smoothTransition")); element.addEventListener("animationend", element.classList.remove("smoothTransition"));
Sadly no transition is happening. Without the eventListener the transition is happening. Also the eventListener does trigger, right after the transition starts.
Advertisement
Answer
Your issue is in your addEventListener:
element.addEventListener("webkitAnimationEnd", element.classList.remove("smoothTransition")); element.addEventListener("animationend", element.classList.remove("smoothTransition"));
The second argument of addEventListener must be a a function and not the result of a function call (in your case undefined). Hence, change the previous lines to:
element.addEventListener("webkitAnimationEnd", function(e) { this.classList.remove("smoothTransition") }); element.addEventListener("animationend", function(e) { this.classList.remove("smoothTransition") });
You may consider to add your event listeners before transitions.
document.addEventListener("DOMContentLoaded", function(e) { var element = document.querySelector('.box'); element.addEventListener("webkitAnimationEnd", function(e) { this.classList.remove("smoothTransition"); console.log('webkitAnimationEnd'); }); element.addEventListener("animationend", function(e) { this.classList.remove("smoothTransition"); console.log('animationend'); }); element.classList.add("smoothTransition") element.classList.toggle("fullscreen") });
.box { width: 150px; height: 150px; background: red; margin-top: 20px; margin-left: auto; margin-right: auto; } @keyframes colorchange { 0% { background: yellow } 100% { background: blue } } .smoothTransition { animation: colorchange 2s; } .fullscreen { width: 100%; height: 100vh; }
<div class="box"></div>