How to make fade out effect with pure JavaScript?

Sometimes, we want to make fade out effect with pure JavaScript.

In this article, we’ll look at how to make fade out effect with pure JavaScript.

How to make fade out effect with pure JavaScript?

To make fade out effect with pure JavaScript, we use CSS transitions.

For instance, we write

<p>Some text before</p>
<div id="target">Click to fade</div>
<p>Some text after</p>

to add some elements.

Then we write

#target {
  height: 100px;
  background-color: red;
  transition: opacity 1s;
}

to add a 1 second transition effect on the div with transition: opacity 1s;.

Then we write

const target = document.getElementById("target");

target.addEventListener("click", () => (target.style.opacity = "0"));
target.addEventListener("transitionend", () => target.remove());

to set the div’s opacity to 0.

After the transition is done, we remove the div with remove.

Conclusion

To make fade out effect with pure JavaScript, we use CSS transitions.