I
I
Igor Fedorov2015-10-04 06:16:23
css
Igor Fedorov, 2015-10-04 06:16:23

Is it possible to change colors in SVG?

Good afternoon. Is it possible to change the colors (fills) of certain elements in SVG using Jquery?

Let's say there are several buttons, for example, red, blue, purple, green.
So that when you click on them, the color of one element in SVG changes.

Thank you all in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Inchin ☢, 2015-10-04
@igor-fedorov

Get the desired element and elem.setAttribute("fill", color);.

<svg width="200" height="200">
  <rect width="100" height="100" x="50" y="50"
        fill="none" stroke="gold"
        stroke-width="10"/>
  <rect width="160" height="160" x="20" y="20"
        fill="none" stroke="yellowgreen"
        stroke-width="10%"/>
</svg>

<div>
    <button data-color="orange">Оранжевый</button>
    <button data-color="tomato">Томатный</button>
</div>

document.querySelector("div").onclick = function(e){
   var t = e.target;
   if(t.parentNode===this) 
       document.querySelector("rect").setAttribute("fill", t.dataset.color);
}

Live: jsfiddle.net/In4in/gyqpvwbu
$("div").on("click", "button", function(){
       $("rect").attr("fill", $(this).data("color"));
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question