37: SVG and JavaScript/DOM Events

(Updated on )

When you use inline <svg>, all the elements are in the DOM, just like <div>s and <span>s and any other HTML element.

If you have SVG like:

<svg>
  <rect id="foo" x="10" y="10" width="100" height="100" />
</svg>

and you do:

var rect = document.getElementById("foo");

you’ll get a reference to that <rect>.

And not only that, you can attach event listeners that work just as you’d expect. And you can adjust attributes and anything else you’d expect to be able to do with JavaScript.

There is at least one gotcha though, that has got me. We often attach event listeners to links, progressive enhancement style. In non-trivial JavaScript architecture, it’s likely those event listeners pass the event around to other functions that handle the functionality. Relying on the this keyword in those situations gets tricky and often isn’t recommended. Instead, since you have the event, you can use event.target. This can be just as tricky though, since with inline SVG the target could be the link, the SVG element itself, or any of the SVG shapes at all.

The solution is to traverse back up the DOM to an expected place. Or try and avoid the situation at all with:

svg {
  pointer-events: none;
}

Which I’d recommend if you don’t plan on using any interactivity within the SVG themselves.