truly-daunting truly-daunting - 6 months ago 28
jQuery Question

How can I desaturate an image that is linked in an SVG?

I'm trying to desaturate the linked image in my SVG when a button is clicked (I need it to load in colour initially).

I've tried doing this:

$("#greyOut").click ( function() {
$("#image1").css("filter", "grayscale(100%)");

I have also tried doing this:

$("#greyOut").click ( function() {

filter: grayscale(100%);

My SVG code looks like this:

<svg version="1.1" id="mySVG" viewBox="0 0 1036.1863 541.28723" height="152.76329mm" width="292.43481mm">
<defs id="defs1"/>
<g transform="matrix(1,0,0,1,5.3227865,-408.7683)" id="svgGroup" style="fill:none">
<image xlink:href="adamPNG.png" y="416.47034" x="-5.3228474" id="image1" preserveAspectRatio="none" height="533.58521" width="1029.7035" />

//I've a lot of paths here so I've cut them out for my question

<path id="path1""fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1">

I have also tried calling just
and not the id, but that doesn't work either. Is it possible to change the CSS of a linked image, or should I just set the
attribute of the
to a desaturated version of my image?


It will work if I do this:

$("#greyOut").click ( function() {
$('image').attr('xlink:href', 'adamPNGgrey.png');

I would still prefer to do this with CSS rather than linking in another image, if it's possible...


If you can edit the SVG I have a solution with SVG filters. In the code snippet doesn't work, I put a external jsfiddle.

 $("#greyOut").click(function() {);


PS Doesn't work in IE11


For IE you can do this, before you check the browser and use the first jQuery for Firefox, Chrome, etc and the second for IE:

 $("#greyOut").click(function() {
   $("#filter image").attr("filter", "url(#grayscale)");