SVG with JavaScript: DOM, events and coordinates

Script inline SVG safely: create elements with createElementNS, convert pointer coordinates, drag shapes, measure paths, and control SMIL animation.

Inline SVG is part of the page’s DOM. You can select its elements, read and set attributes, listen for events and build new shapes, using the same APIs you use for HTML. A few SVG-specific rules, mainly namespaces and coordinate systems, account for most of the surprises.

The live editors on this page run with scripts disabled, so they show the markup your scripts would work on. The scripts themselves are in the code blocks.

Where scripts can run

Script works when the SVG is inline in an HTML page. It does not work when the SVG is used as an image: MDN states that JavaScript is disabled for SVG used through <img>, CSS background-image and similar. MDN adds that those restrictions do not apply when SVG is viewed directly or embedded as a document with <iframe>, <object> or <embed>. If you need behavior, inline the SVG or embed it as a document. See SVG security before you embed files you did not write.

Selecting and changing elements

Inline SVG elements answer to querySelector, classList and setAttribute. Geometry values are attributes, so you change them with setAttribute.

A script that updates this chart reads the data-value attributes and writes new heights:

for (const bar of document.querySelectorAll(".bar")) {
  const value = Number(bar.dataset.value);
  bar.setAttribute("height", value);
}

Changing the class or CSS custom properties and letting a stylesheet do the visual work is usually cleaner than setting many attributes in script. The hover color in the example above lives in CSS for that reason.

Creating elements: use createElementNS

SVG elements belong to the namespace http://www.w3.org/2000/svg. Calling document.createElement("circle") creates an HTML-namespace element that the browser will not draw. MDN’s page on createElementNS() says exactly this: you need the namespaced call to get a proper SVG element.

const NS = "http://www.w3.org/2000/svg";
const svg = document.querySelector("#chart");

function bar(x, value) {
  const rect = document.createElementNS(NS, "rect");
  rect.setAttribute("x", x);
  rect.setAttribute("width", 30);
  rect.setAttribute("y", 100 - value);
  rect.setAttribute("height", value);
  rect.setAttribute("class", "bar");
  return rect;
}

[40, 80, 60].forEach((v, i) => svg.append(bar(20 + i * 40, v)));

Attribute names set with setAttribute are plain names such as viewBox and stroke-width. Note the capital B in viewBox. Setting a property through element.style follows CSS rules, so there you use style.strokeWidth or style.setProperty("stroke-width", "2").

Avoid building SVG by assigning strings to innerHTML when any part of the string comes from users. That is an injection route. SVG security covers it.

Coordinates: from the mouse to the drawing

Pointer events report positions in CSS pixels relative to the page or viewport, but your shapes live in user units set by the viewBox and any transforms. To convert, use the element’s screen transform matrix.

getScreenCTM() returns a DOMMatrix that maps the element’s local coordinates to the screen. Invert it and apply it to a point, and you get from client coordinates back to local ones. MDN’s page confirms the return value and the inverse() and matrixTransform() steps. It also warns that a degenerate matrix, such as scale(0), cannot be inverted.

function toSvgPoint(svg, event) {
  const point = new DOMPoint(event.clientX, event.clientY);
  return point.matrixTransform(svg.getScreenCTM().inverse());
}

Call this on the <svg> element, or on a nested element if you want coordinates inside that element’s own transform. This one function removes the need to hand-compute offsets for scrolling, scaling or a responsive viewBox. See SVG viewBox and SVG transforms for how those stack up.

Dragging with pointer events

Pointer events give one model for mouse, pen and touch. setPointerCapture() keeps sending events to your element even when the pointer leaves it, which is what you want for a drag.

const svg = document.querySelector("svg");
const handle = svg.querySelector("#handle");

handle.addEventListener("pointerdown", (e) => {
  handle.setPointerCapture(e.pointerId);
});

handle.addEventListener("pointermove", (e) => {
  if (!handle.hasPointerCapture(e.pointerId)) return;
  const p = toSvgPoint(svg, e);
  const x = Math.min(190, Math.max(30, p.x));
  handle.setAttribute("cx", x);
});

The touch-action: none in the markup stops the browser from claiming the gesture for scrolling or zooming. MDN notes that when the browser takes over a gesture, it fires pointercancel, so handle that event too. Test dragging on a real touch device. Attach handlers to specific elements instead of the whole document, and keep the handler body small.

Why clicks sometimes miss

By default, SVG hit testing uses pointer-events: visiblePainted. A shape with fill="none" is clickable only on its stroke. Clicks in the middle pass through to whatever is below. If you want the whole interior to respond, set pointer-events: fill or all.

Measuring: getBBox and getTotalLength

getBBox() returns the bounding box of an element in its own user coordinate system. MDN is explicit that it ignores transforms on the element and its parents, and that stroke is excluded unless you pass { stroke: true }. Use it to place labels or draw a highlight box. Use getBoundingClientRect() when you need on-screen pixels.

getTotalLength() returns the length of a path in user units. It is the usual way to set up a stroke draw-on effect, as shown in SVG animation:

const path = document.querySelector("#route");
const length = path.getTotalLength();
path.style.strokeDasharray = length;
path.style.strokeDashoffset = length;

Controlling SMIL animation from script

If the SVG uses SMIL, script can steer it. Give an animation element begin="indefinite" and call beginElement() to start it. pauseAnimations() on the <svg> element suspends the animation clock for everything in that fragment.

document.querySelector("#grow").beginElement();
document.querySelector("svg").pauseAnimations();

For CSS and Web Animations API animation, see SVG animation. pauseAnimations() is also the hook for honoring reduced-motion settings in SMIL.

Event delegation for many shapes

A map or chart can have hundreds of shapes. Instead of one listener per shape, attach one listener to the <svg> and look at event.target.

svg.addEventListener("click", (event) => {
  const region = event.target.closest("[data-region]");
  if (!region) return;
  console.log(region.dataset.region);
});

This also covers shapes you add later. For keyboard access and screen reader support on interactive shapes, see interactive infographics and SVG accessibility.

When to reach for a library

Plain DOM code is enough for tooltips, highlights, toggles and simple data-driven shapes. If you find yourself rebuilding the whole drawing on every change, a framework’s templating handles that better. Continue with SVG in frontend frameworks.

Sources

Checked against these references on 2026-11-21.