1

I have an SVG image that is embedded inside 'img src' tag. The svg contains different paths with a color, each separated by id. I want to change the fill color inside each id using jquery

Below are the codes i've used. But the color is not changing. By searching a lot, i found that if svg is added directly to the html, it will work. A working example: http://jsfiddle.net/P6t2B/

But how can I achieve it if it is done via 'img src' to add svg??

Inside html:

<img src="images/hands.svg" width="70px"/>

JQuery code change fill color id 'l1':

$('#l1').css({fill:"#000000"});

Sample SVG:

<path id="l1" fill="#ffffff" d="M85.6,227.3L85.6,227.3c14.2-5.7,21.1-22,15.3-36.2l-35.4-87.5c-2.5-6.1-9.5-9.1-15.6-6.6
    l-29.3,11.9c-6.1,2.5-9.1,9.5-6.6,15.6L49.4,212C55.1,226.1,71.4,233,85.6,227.3z"/>
<path id="l2" fill="#ffffff" d="M133.8,206.6L133.8,206.6c15.2-1.5,26.4-15.2,24.9-30.4L142.7,55.9
    c-0.6-6.6-6.5-11.4-13.1-10.8l-31.4,3.1c-6.6,0.6-11.4,6.5-10.8,13.1l16.1,120.3C104.9,196.9,118.6,208.1,133.8,206.6z"/>
<path id="l3" fill="#ffffff" d="M181.8,219.6L181.8,219.6c15,3,29.7-6.8,32.7-21.8l22.8-151.7c1.3-6.5-2.9-12.8-9.4-14.1
    l-31-6.2c-6.5-1.3-12.8,2.9-14.1,9.4L160,186.9C157,201.9,166.9,216.6,181.8,219.6z"/>
<path id="l4" fill="#ffffff" d="M227.8,247.1L227.8,247.1c13.9,6.5,30.5,0.4,37-13.4l58.1-142c2.8-6,0.2-13.2-5.8-16
    l-28.6-13.4c-6-2.8-13.2-0.2-16,5.8l-59.4,137.7C206.6,219.7,208.3,238,227.8,247.1z"/>
<path id="l5" fill="#ffffff" d="M257.1,245.1l51.8-41l37,0.5l24.5,15.4L337.7,256l-90.1,90.2l-31.6,15.9
    C216.1,362.1,184.1,325.9,257.1,245.1z"/>
Gijo Varghese
  • 11,264
  • 22
  • 73
  • 122
  • 1
    this might help - http://stackoverflow.com/a/11978996/5984537 – Saeed Salam Oct 31 '16 at 17:48
  • Gijo, could you try changing the `fill` property value to the variable `currentColor`, and switch colors using the `color` property? Here's a [**fiddle**](http://jsfiddle.net/rickyruizm/2ts87q17/), but cannot test without your image hosted. – Ricky Ruiz Oct 31 '16 at 18:10
  • 1
    If that does not work, you will probably need to use another embedding method, like ``, `` tag is not recommended for svg when you want to have interactions with it, because the `` element will just render as a raster. – Ricky Ruiz Oct 31 '16 at 18:12
  • @Ricky_Ruiz Already tried object method. Not working – Gijo Varghese Oct 31 '16 at 18:20

1 Answers1

0

This may do the trick.

$('img.svg').each(function(){
    var $img = $(this);
    var imgClass = $img.attr('class');
    var imgURL = $img.attr('src');

    $.get(imgURL, function(data) {
        var $svg = $(data).find('svg');
        if(typeof imgClass !== 'undefined') {
            $svg = $svg.attr('class', imgClass+' style-color-black');
        }
        $svg = $svg.removeAttr('xmlns:a');
        $img.replaceWith($svg);
    }, 'xml');

});

source: codedump

Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67