Js Class Remove Not Working Properly, Dev Tools Problem
my purpose is that to animate the DIV Box everytime when browser Tab is active (means i switch the tab to other & back to this tab), As i am adding addEventListener & its w
Solution 1:
This is a speed problem. When you add the class, the browser immediatly assumes no transition is needed, because the element already has the class. You can fix this by delaying your classList.add
a little:
var element = document.getElementById("topHeading");
document.addEventListener("visibilitychange", () => {
var isVisible = document.visibilityState === "visible";
setTimeout(function() {
element.classList[isVisible ? 'add' : 'remove']("r1");
});
});
Fixed Codepen
Solution 2:
Re-applying the class doesn't work. You can get it to work by removing the element from the dom and then adding it again or by introducing a delay. You can read more about restarting css animations at https://css-tricks.com/restart-css-animation/
document.addEventListener("visibilitychange", () => {
var element = document.getElementById("topHeading");
if(document.visibilityState === "visible" ) {
element.classList.add("r1");
} else {
element.parentNode.replaceChild(element.cloneNode(true), element);
}
});
Or you can add the animation class to the html element and write less JS:
document.addEventListener("visibilitychange", () => {
var element = document.getElementById("topHeading");
if(document.visibilityState === "visible" ) {
element.parentNode.replaceChild(element.cloneNode(true), element);
}
});
Post a Comment for "Js Class Remove Not Working Properly, Dev Tools Problem"