How to Create a Blur Animation in JavaScript?

Estimated read time 1 min read

You can create a blur animation in JavaScript using the CSS filter property and JavaScript to change the value over time. Here’s an example of how you can do this:

  1. Create a HTML element that you want to animate, for example a div:
<div class="blur-element"></div>
  1. Apply the CSS filter property to the element with the blur value set to 0:
.blur-element {
  width: 100px;
  height: 100px;
  background-color: red;
  filter: blur(0px);
  transition: filter 0.5s ease;
}
  1. In JavaScript, you can use the setInterval function to increment the blur value over time:
let blurValue = 0;
setInterval(function() {
  blurValue += 0.5;
  document.querySelector(".blur-element").style.filter = `blur(${blurValue}px)`;
  if (blurValue >= 5) {
    blurValue = 0;
  }
}, 50);

This will create an animation that gradually blurs the element over time, and resets the blur value back to 0 after it reaches 5 pixels. You can adjust the speed of the animation by changing the interval time in the setInterval function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply