Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect state of CSS transition via JS and skip it

Consider such div:

<div id="someid"></div>

And it's style:

#someid {
  transition: background-color 10s ease;
  background-color: #FF0000;
  height: 100px;
  width: 100px;
}

#someid:hover {
  background-color: #FFFFFF;
}

I want to have a possibility to detect state (currently animating or not) of #someid via JS and/or end animation if that's possible. I've tried a thing from this answer:

document.querySelector("#someid").style.transition = "none";

but it didn't work for currently animating element.

The point is I need to detect whether element is animating now and if so, wait for animation to end or end it immediately, otherwise do nothing

I've already found transitionend event, but using it I can't detect whether element is animating at the moment.

like image 645
fas Avatar asked Aug 31 '25 20:08

fas


1 Answers

You can listen to transition event and remove it on demand:

const el = document.getElementById('transition');
let isAnimating = false;

el.addEventListener('transitionstart', function() {
  isAnimating = true;
});

el.addEventListener('transitionend', () => {
  isAnimating = false;
});

el.addEventListener('transitioncancel', () => {
  isAnimating = false;
});

function removeTransition(checkIfRunning) {
  if (checkIfRunning && !isAnimating) {
    return;
  }

  el.style.transition = "none";
}
#transition {
  width: 100px;
  height: 100px;
  background: rgba(255, 0, 0, 1);
  transition-property: transform background;
  transition-duration: 2s;
  transition-delay: 1s;
}

#transition:hover {
  transform: rotate(90deg);
  background: rgba(255, 0, 0, 0);
}
<div id="transition">Hello World</div>
<br />
<button onclick="removeTransition(false)">Remove Transition</button>
<br />
<br />
<button onclick="removeTransition(true)">Remove Transition on if running</button>
like image 112
Dipen Shah Avatar answered Sep 03 '25 09:09

Dipen Shah