Chain Trap Chain Trap - 4 months ago 14
Javascript Question

How to use data-* attribute with SVG Circle element

I want to update the css property

fill
of the Circle element (e.g, from blue to red) when it is clicked with the jQuery
.css()
method and through the data-* attribute.

EXAMPLE:

CSS

svg {
height: 200;
width: 200;
}
circle {
fill: blue;
}


JAVASCRIPT

jQuery(function(){
$(document).on("click", "[data-update]", function(){
var circle = $(this).find("circle");
circle.css({ fill: "red" });
});
});


HTML

<svg data-update>
<circle cy="100" cx="100" r="50"></circle>
</svg>


The link for the demo is here.

So if I add a value (e.g, green) to the
data-update
attribute:

data-update="green"


Then what particular code should I change or add inside the script in order to change the Circle element's color?

Any idea?

Answer

You simply need to get the value of the attribute. Demo.

jQuery(function(){
  $(document).on("click", "[data-update]", function(){
    var circle = $(this).find("circle");
    circle.css({
      fill: $(this).data('update') // <-- get value
    });
  });
});

<svg data-update="green">
  <circle cy="100" cx="100" r="50"></circle>
</svg>
Comments