Home > Enterprise >  Replace jQuery visibility and opacity animation with pure Javascript
Replace jQuery visibility and opacity animation with pure Javascript

Time:05-27

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);

CodePudding user response:

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>

CodePudding user response:

It seems to me that @RoryMcCrossan nailed it with his answer. What is still unclear to me is: Why do we need to set the visibilty at all? I copied and modified his snippet and removing all references to visibility in it and it seems to work in just the same way. What am I missing? Is it really redundant?

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

document.querySelector('button').addEventListener('click', () => {
  square.classList.toggle('show');
});
#square {
  width: 200px;
  height: 200px;
  background-color: #C00;
  opacity: 0;
  transition: 1s;
}
#square.show {
  opacity: 1.0;
}
<button>Toggle the square...</button>
<div id="square"></div>

  • Related