6

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

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

4 Answers 4

10

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%)";
2
  • any idea how to combine two filters? say brightness and invert? Sep 17, 2014 at 21:57
  • 1
    @MaciejJankowski just separate them with a space, "brightness(50%) invert()": jsfiddle.net/bj4p0sxm
    – Pavlo
    Sep 17, 2014 at 23:39
3
image.style["-webkit-filter"] = "brightness(50%)";
0
2

Add that filter to a class:

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

And toggle that class:

image.classList.toggle('bright');
1
  • @PavloMykhalov: Well, neither are -webkit properties.
    – Blender
    Feb 13, 2013 at 10:00
-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/

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.