Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace jQuery visibility and opacity animation with pure Javascript

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);
like image 263
Matias Avatar asked May 05 '26 07:05

Matias


1 Answers

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>
like image 154
Rory McCrossan Avatar answered May 06 '26 20:05

Rory McCrossan



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!