Home > Net >  How do I add an transition animation by toggling a class?
How do I add an transition animation by toggling a class?

Time:12-02

I have some elements need to be highlighted/unhighlighted conditionally.

So I have a class called highlight given to any element that need to be highlighted with a transition animation.

The problem is I can't animate it when the highlight class is removed.

Because any element could be highlighted so I couldn't find a specific selector for them.

I could do this but it just doesn't seem right to me:

* {
  transition: background-color 1s;
}

Is there a better way to achieve it?

Here's a simplified example to demonstate my issue:

[...document.querySelectorAll('body *')].forEach(e => e.addEventListener('click', () => e.classList.toggle('highlight')));
.highlight {
  background-color: red;
  transition: background-color 1s;
}
<h2>Click anything to toggle highlight</h2>

<p>Hello</p>
<p>World</p>
<p>Thanks</p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Do the logic differently

[...document.querySelectorAll('body *')].forEach(e => e.addEventListener('click', function(e) {
  e.target.classList.toggle('bg');
  e.target.classList.add('highlight'); /* always add highlight */
}));
/* remove highlight when the transition is done */
[...document.querySelectorAll('body *')].forEach(e =>
  e.addEventListener('transitionend', function(e) {
    e.target.classList.remove('highlight');
  })
);
.highlight {
  transition: background-color 1s;
}

.bg {
  background: red;
}
<h2>Click anything to toggle highlight</h2>

<p>Hello</p>
<p>World</p>
<p>Thanks</p>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related