Let's say I want to apply a series of CSS filters to an image. Here's my image:
var img = document.getElementById("my_image.png");
And here are the <input type="range">
sliders that applies the filters:
var slider1 = document.getElementById("slider1");
var slider2 = document.getElementById("slider2");
I add an event listener to each:
slider1.addEventListener("input", function(){
img.style.filter = ( "sepia(" + this.value + ")" );
});
slider2.addEventListener("input", function(){
img.style.filter = ( "blur(" + this.value + "px)" );
});
When I move the second slider it's going to erase the filter property of the first. But if I +=
the filter properties, it's going to add to the img.style.filter
string every single step of the slider. If I use a "change" event listener, the user isn't going to get the benefit of the live "preview" of the filter effect. (And if a user comes back to the slider for a second go, it's going to result in an erroneous img.style.filter
property).
So what's the best javascript-only (no jquery) way of only updating the relevant part of the img.style.filter
property when the relevant slider is manipulated while retaining the live rendering effect?
Here you go. https://jsfiddle.net/2p8kwjv1/1/
Apparently if you want multiple filters you have to define them in the same filter definition. like so
img{
filter: blur(50px) sepia(50%);
-webkit-filter: blur(50px) sepia(50%);
}
So to achieve this in javascript you have to keep references to these values. Then every time you change the sepia, you can also apply the current blur value to display two filters at the same time, dynamically.
var sepia = slider1.value;
var blur = slider2.value;
slider1.addEventListener("input", function(){
sepia = this.value;
img.style["-webkit-filter"] = "blur("+blur+"px) sepia(" + this.value + "%)";
});
slider2.addEventListener("input", function(){
blur = this.value;
img.style["-webkit-filter"] = "blur(" + this.value + "px) sepia("+sepia+"%)" ;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With