I have an svg file containing a group with a single line element. I can make use of the use
element and make several reference copies in any position I want them. However, I want to use javascript to add and remove the use
element dynamically. Is there a way to use javascript to insert an svg use
element of my line into my group?
<svg version="1.1" id="ex1-3rds-quarter-s" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
y="0px" width="323.333px" height="55.333px" viewBox="0 0 323.333 55.333" enable-background="new 0 0 323.333 55.333"
xml:space="preserve">
<g id="ledgerlines">
<line id="MidCLine1" fill="none" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" x1="48.09" y1="41.694" x2="57.924" y2="41.694"/>
</g>
</svg>
Since SVG images can be inlined in HTML, we can manipulate them with JavaScript. This means that we can animate parts of an image from code, make it interactive, or turn things around and generate graphics from data. In this example, we are going to create a watch.
Contrary to the rules in CSS 2.1, the z-index property applies to all SVG elements regardless of the value of the position property, with one exception: as for boxes in CSS 2.1, outer 'svg' elements must be positioned for z-index to apply to them.
svg is a markup language, meaning that you can use css selector libraries such as jquery to interact with the given svg. You can query the svg in order to get an element by its id, or get an array of elements selected by class. You can attach event handlers to them such as click , mouseover , mouseenter , etc.
The <g> SVG element is a container used to group other SVG elements. Transformations applied to the <g> element are performed on its child elements, and its attributes are inherited by its children. It can also group multiple elements to be referenced later with the <use> element.
var svgns = "http://www.w3.org/2000/svg";
var xlinkns = "http://www.w3.org/1999/xlink";
// Get a reference to the <g> element
var g = document.getElementById("ledgerlines");
// Create a <use> element
var use = document.createElementNS(svgns, "use");
// Add an 'href' attribute (using the "xlink" namespace)
use.setAttributeNS(xlinkns, "href", "#MidCLine1");
// Offset the line down by 10
use.setAttribute("y", "10"); // offset = y+10
// Add the <use> to the <g>
g.appendChild(use);
Demo here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With