6

How to dynamically apply CSS filters? I have tried the following for Chrome.

image.style = "-webkit-filter: brightness(50%);";

4 Answers 4

11

You should set value to the webkitFilter property, not to the style object. This syntax will work:

image.style.webkitFilter = "brightness(50%)";

If you don't know JavaScript property name, you can reference it by CSS property (like karaxuna suggested, will work too):

image.style["-webkit-filter"] = "brightness(50%)";
Sign up to request clarification or add additional context in comments.

2 Comments

any idea how to combine two filters? say brightness and invert?
@MaciejJankowski just separate them with a space, "brightness(50%) invert()": jsfiddle.net/bj4p0sxm
3
image.style["-webkit-filter"] = "brightness(50%)";

Comments

2

Add that filter to a class:

.bright {
    -webkit-filter: brightness(50%);
}

And toggle that class:

image.classList.toggle('bright');

1 Comment

@PavloMykhalov: Well, neither are -webkit properties.
-1

1) Check if browser supports css-filters (if needed)
2) Detect if "filter" property needs vendor in current browser and save it
3) Set filter value in format:

el.style["-vendor-filter"] = value;

or

el.style.vendorFilter = value;

Check small demo for it: http://codepen.io/malyw/pen/EDnmt
Also you can find large demo showing css filters in action: http://malyw.github.io/css-filters/

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.