Len
Len

Reputation: 123

javascript to change colour of an svg shape

Hi is there a way of using javascript for example using buttons to change colour of an svg shape? If so could someone please guide me in the right direction thanks

Upvotes: 3

Views: 20998

Answers (2)

Phrogz
Phrogz

Reputation: 303166

Here's an example of using JS to create animation elements to highlight colors based on mouse over/out:
http://phrogz.net/SVG/change-color-on-hover.svg

Here's an example of an SVG that changes lots of colors, and house some silly mouseover buttons:
http://phrogz.net/SVG/rgbhsv.svg

Here's an example that shows SVG in XHTML, with both native HTML widgets (an HTML5 slider) as well as draggable SVG elements (the path handles):
http://phrogz.net/SVG/area_of_path.xhtml

In general:

  1. Find elements
  2. Attach event handlers
  3. In the event handlers, adjust properties (either via setting XML attributes or via the SVG DOM)

Upvotes: 0

Phil H
Phil H

Reputation: 20131

If you have a number of these shapes, then look at the d3 library, which is designed explicitly to allow you to bind data to svg attributes. A good explanation of the way it works is the Three little circles tutorial.

If you want to just change an attribute of an svg shape on a button click, then you need an onclick handler for the button:

function handleClick() {
    // code to modify svg here, e.g.:
    document.getElementById('svgShapeId').setAttribute('cx',150);
}

document.getElementById('buttonId').onclick = handleClick;

Upvotes: 4

Related Questions