user3186555
user3186555

Reputation:

How can I detect the animationend event on a pseudo element?

I know how to detect an animationend event with a regular DOM element, but how do you do it with a pseudo-element?

I know the event to look for is animationend, but how do I attach the pseudo-element with a handler using that event?

I have tried the following, but I can't seem to get it to work.

document.querySelector("#someSelector:after").addEventListener("animationend",...,false)

How can I do this in vanilla JavaScript?

Upvotes: 7

Views: 1619

Answers (1)

Robin James Kerrison
Robin James Kerrison

Reputation: 1757

:after pseudo-elements can't be selected as though they're part of the DOM, because, in short, they're not part of the DOM. That being said, it is possible to get the event triggers you'd expect, as they're fired on the "parent" of the :after.

For example, if you have your :after on a DOM element with id of 'containybox', then you can grab that DOM element and trigger on its animationend. The event will then fire when the :after's animation ends.

var containerBox = document.getElementById('containybox');    

containerBox.addEventListener('animationend', function() {
  console.log("Animation ended!");
});

Full working snippet:

var containerBox = document.getElementById('containybox');

containerBox.addEventListener('animationend', function() {
  console.log("Animation ended!");
});

containerBox.addEventListener('transitionend', function() {
  console.log("Transition ended!");
});
#containybox {
  position: relative;
  width: 100px;
  height: 100px;
  background: #fadebc;
  padding: 10px;
  text-align: center;
}
#containybox:after {
  content: "Standard aftermibob.";
  display: block;
  position: fixed;
  left: 120px;
  width: 100px;
  height: 100px;
  background: #bcdefa;
  animation: animatedBackground 1000ms linear;
}
#containybox:hover:after {
  background: #bcfade;
  transition: background-color 1000ms linear;
}
@keyframes animatedBackground {
  from {
    background-color: #000000;
  }
  to {
    background-color: #bcdefa;
  }
}
<div id="containybox">
  Just a standard containybox.
</div>

Upvotes: 4

Related Questions