dougblitz210 dougblitz210 - 7 months ago 11
Javascript Question

Using the CSS "filter" property with jQueries css method

It seems I cannot apply the css "filter" property with the .css method in jQuery. Other properties seem to work okay when they are written this way, but not the filter property... jsFiddle here:

https://jsfiddle.net/md2100/fwcdzhu2/

Here's what my current code looks like.

HTML:

<h2>This is a heading</h2>
<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>
<p>This is a paragraph.</p>
<button>Set background-color of p</button>


Javascript:

$(document).ready(function(){
$("button").click(function(){
$("p").css("filter", "invert(100%)");
});
});

Answer

You need to set the filter attribute if you are trying to set the filter via .css() - Also, you need to include the browser prefixing to make it work in chrome, opera, and safari.

Keep in mind that filter does not have full cross-browser support!

$("p").css({"-webkit-filter": "invert(100%)", "filter": "invert(100%)"});

Demo: https://jsfiddle.net/fwcdzhu2/2/