4

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?

1
  • don't forget vendor prefixes! Commented Nov 25, 2015 at 16:58

1 Answer 1

5

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+"%)" ;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.