FrozenYoghurt
FrozenYoghurt

Reputation: 127

Blur an image with JavaScript

I want to make something like a Slideshow, but if you press a button for the next Picture, it should blur out until it's unrecognizable and then the next should appear blurred and become sharp.

The problem here is, I would have to apply the blur via JS and my current approach looks like this: document.getElementById("no1").style.filter = "blur(3Px)";

If I apply the blur with CSS it works just fine, but I need it to apply when the button is clicked, which does not work. The object I am trying to blur is an <img>

Also, it would be good to know, if there is something like a waiting condition or if additional steps in the function will wait for the transition duration of the blur to be done before starting.

Upvotes: 5

Views: 17948

Answers (2)

user128511
user128511

Reputation:

const img = document.querySelector('img');
img.addEventListener('click', toggleBlur);

function toggleBlur() {
  this.classList.toggle('blur');
}
img { transition: filter 1s linear; }
.blur { filter: blur(30px); }
<img src="https://i.imgur.com/KjUybBD.png"></img>

Works for me in Chrome, Firefox, Safari, latest Edge...

enter image description here

Upvotes: 13

Roy
Roy

Reputation: 8069

Although gman's solution is a more solid one (toggling a CSS class via JS), this simple approach with applying the filter via JavaScript also works:

var btn = document.getElementById('blurBtn');
var img = document.getElementById('blurImg');

btn.addEventListener('click', addBlur)

function addBlur() {
  img.style.filter = 'blur(3px)';
}
<img id="blurImg" src="https://i.imgur.com/2fGfQua.gif">
<button type="button" id="blurBtn">Blur</button>

Upvotes: 1

Related Questions