1

I'm trying to remove jQuery from an old website but I'm stuck with this animation they have.

I can only replicate the opacity fade, but I don't seem able to transition the visibility slowly it just goes 1 or 0, how can I do both thing smoothly?

$("#square").css({ opacity: 0.0, visibility: "visible" }).animate({ opacity: 1.0 }, 200);

$("#square").css({ opacity: 1.0, visibility: "hidden" }).animate({ opacity: 0.0 }, 200);
Matias
  • 190
  • 13
  • Does this answer your question? [Pure JS equivalent of jQuery .animate()](https://stackoverflow.com/questions/15521081/pure-js-equivalent-of-jquery-animate) – Simone Rossaini May 26 '22 at 13:49
  • I gave that question and the animate API a small read before asking but I'm still confused on how to do both, the opacity and visibility at the same time. – Matias May 26 '22 at 13:53

1 Answers1

1

The simplest (and by far the most performant) option here is to use CSS for animations. JS animation should be avoided as much as possible as it's slow and not hardware accelerated.

To do what you require in CSS the key rule to apply is transition. You can use this to control the properties to be animated, their delay, execution time etc. More information is available at MDN.

Here's a rudimentary example. Note that JS is only used to add the class to trigger the animation - it does not control the animation at all.

let square = document.querySelector('#square');

document.querySelector('button').addEventListener('click', () => {
  square.classList.toggle('show');
});
#square {
  width: 200px;
  height: 200px;
  background-color: #C00;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.2s, visibility 0.2s;
  pointer-events: none;
}
#square.show {
  opacity: 1.0;
  visibility: visible;
}
<button>Toggle the square...</button>
<div id="square"></div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thanks for commenting! This is really close to what I've tried, the only thing missing is that it's not applying the visibility change at the end that I need for removing some keyboard events. – Matias May 26 '22 at 14:17
  • 1
    No problem - added that to the `transition` as well – Rory McCrossan May 26 '22 at 14:32