How to Fade In Color Red Using JavaScript?

Estimated read time 1 min read

You can use the setInterval method in JavaScript to change the opacity of an element gradually over time, resulting in a fade-in effect.

Here’s an example of how you can fade in a red colored element with JavaScript:

<div id="redBox"></div>

<style>
  #redBox {
    width: 100px;
    height: 100px;
    background-color: red;
    opacity: 0;
  }
</style>

<script>
  let redBox = document.getElementById("redBox");
  let opacity = 0;
  let fadeIn = setInterval(function() {
    if (opacity >= 1) {
      clearInterval(fadeIn);
    }
    redBox.style.opacity = opacity;
    opacity += 0.1;
  }, 100);
</script>

In the example, setInterval function runs every 100 milliseconds and increases the opacity of the redBox element by 0.1 each time. The loop continues until the opacity reaches 1, and the clearInterval method is called to stop the loop.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply