My goal is to create a CSS animation using jQuery where I add a class with a transition of 0s to change the color, and then promptly remove that class so it gradually returns to its original color (with the original transition of 2s).
The code below illustrates my issue. Why does the blue1() function not work as expected? It seems like the JavaScript executes too quickly for the new class to be added to the element, but I'm unsure about the inner workings of this process. However, if I add the class and then wait before removing it, as shown in blue2(), it works fine. Is there a more effective way to achieve this effect? What would be the optimal workaround?
Thank you.
Snippet:
function blue1(){
$("#element").toggleClass("blue");
$("#element").toggleClass("blue");
}
function blue2(){
$("#element").toggleClass("blue");
setTimeout(function(){
$("#element").toggleClass("blue");
}, 1000);
}
#element{
width:100px;
height:100px;
background:red;
transition:2s;
}
#element.blue{
background:blue;
transition:0s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="element"></div>
<button id="button" onclick="blue1();">Run without delay</button>
<button id="button2" onclick="blue2();">Run with delay</button>
</body>
</html>