Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript event listener for SVG transform

SVG can perform transformations like so

<g transform="translate(80,0)">

Also, whenever this attribute is manipulated by javascript for example the SVG will move to the new point. (or scale etc.)

I was wondering whether it was possible to set an event listener that runs each time any SVG object in the document is changed. This is more of a concept question of how do browsers keep polling all the SVG elements and is there a nice way to intercept that change.

I tried doing my homework understanding how SVGs work and it seems like they have a transformation matrix that can be accessed via the DOM. The question is how does the browser know when to make that change.

References:

  1. http://www.w3.org/TR/SVG/struct.html
  2. https://www.dashingd3js.com/svg-group-element-and-d3js
  3. http://sarasoueidan.com/blog/svg-transformations/

In short, is there an event listener in javascript that can be built to listen for changes of SVG's in genereal

like image 339
cjds Avatar asked Dec 25 '14 20:12

cjds


2 Answers

You can use a mutation observer to listen to DOM changes. This won't react to SMIL changes though, just attribute and element changes.

Mutation events may contain multiple DOM changes as they are sent asynchronously.

like image 176
Robert Longson Avatar answered Oct 31 '22 18:10

Robert Longson


This is a very good question, for me SVG is like a Frankenstein but in a good way, you can animate SVG using the DOM, CSS or Javascript and is widely supported on these days. This sentence in the W3 is relevant:

[...] After the first modification the object becomes live, such that any modifications made to the corresponding attribute are immediately reflected in the object.

The SVG DOM builds upon and is compatible with DOM elements, so you can have all the event listeners you use normally with the DOM (click, hover, load..). Apart of that, I think the more important are this 3:

beginEvent: Occurs when an animation element begins. For details, see the description of Interface TimeEvent in the SMIL Animation specification.

endEvent: Occurs when an animation element ends. For details, see the description of Interface TimeEvent in the SMIL Animation specification.

repeatEvent: Occurs when an animation element repeats. It is raised each time the element repeats, after the first iteration. For details, see the description of Interface TimeEvent in the SMIL Animation specification.

Complete list of supported events

If you need more than that then my advice is to check the SMIL Animation Model

like image 1
Tom Sarduy Avatar answered Oct 31 '22 17:10

Tom Sarduy