Here is an example of my problem
I have an div
and a button
. Each time the button is clicked, the div
changes it's background-color
to a random color.
button.addEventListener('click', function(e){
e.preventDefault();
setRandomColor();
});
By default the the div
has a class called transition-on
which applies a transition to the background-color
.
<div class="block transition-on"></div>
<button>Change</button>
CSS:
.transition-on {
transition: background-color 0.5s
}
If I remove this class before I apply the random background-color
then reapply the class after, the transition will still apply.
My intention is to remove the transition temporarily when I apply the random color.
button.addEventListener('click', function(e){
e.preventDefault();
block.classList.remove('transition-on');
setRandomColor();
block.classList.add('transition-on');
});
Does anybody know why this may be happening?
EDIT:
Referring to the answer by @ths - Using a setTimeout
does produce the result that I need but now I am wondering why is it necessary to use a timeout.
Is a timeout really required to temporarily disable a css transition?
- Remove the transition class
- Apply the color to the block
- Add the transition class back
This should logically change the color without a transition