Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect if element is being transitioned

How to detect via js if any sort of transition is being applied to the element right now?

Short story of my problem:

I have a situation where I'm firing a function on the `transitionend` event, but sometimes the element doesn't have any *transition* being applied (because in Firefox, for example, the user might click some element rapidly which makes the transition goes crazy and stop working) so I want to know when it doesn't work and just fire the function myself, skipping the `transitionend`. I am trying to avoid ugly solutions..
like image 292
vsync Avatar asked Oct 21 '25 02:10

vsync


1 Answers

You can use the Web Animation API for that, notably the Element#getAnimations method, which will return a list of Animation objects applied on the Element. These will include Web Animations (from .animate()), CSS @keyframes animations, and CSS transitions.

document.querySelectorAll("a").forEach((el) => {
  el.onmouseenter = (evt) => {
    const animations = el.getAnimations(); // we could also ask to look in the subtree
    // we're only interested in CSS transitions
    const transitions = animations.filter((anim) => anim instanceof CSSTransition);
    console.log(transitions.length
      ? transitions.map((anim) => anim.transitionProperty )
      : "no transition"
    );
  };
});
a:hover {
  color: red;
  opacity: 0.5;
}
.color-transition {
  transition: color 1s;
}
.color-and-opacity-transition {
  transition: color 1s, opacity 5s;
}

/*SO-only*/.as-console-wrapper { max-height: 110px !important }
<b>Hover these anchors to log their applied transitions.</b><br>
<a class="color-transition">color transition</a><br>
<a class="color-and-opacity-transition">color &amp; opacity transition</a><br>
<a>no transition</a>
like image 157
Kaiido Avatar answered Oct 22 '25 16:10

Kaiido



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!