Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store custom data inside of svg-objects?

I plan to have some (a lot of) objects inside of svg-object that will be generated using JavaScript.

User will do different activities with them: click, mouse-over, mouse-out. Once any event is occurred some data that are object specific are required to be displayed.

Question: how to get data about object? For example, user clicked on rectangle that represents car of "Make A" (there are few rectangles, each of them represents a separate make). How can I determine a make? Is there any way to associate 'external data' with svg-objects?

like image 564
Budda Avatar asked May 16 '11 02:05

Budda


1 Answers

The Event object you get in the click/mouseover/etc-handler has a property called target that is the element (technically any EventTarget, but in this case it's the element) that the event was first dispatched to.

One way to store custom data is to use namespaced attributes. The reason why you should namespace your attributes is that they may clash with existing or future svg attributes.

Here's an example:

var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttributeNS("http://www.example.com/yourcustomnamespace", "data", "whatever-data-you-want-here");
rect.addEventListener("click", myclickhandler, false);
...

function myclickhandler(evt)
{
  var target = evt.target;
  // specialcase for use elements
  if (target.correspondingUseElement)
    target = target.correspondingUseElement;
  alert(target);
  alert(target.getAttributeNS("http://www.example.com/yourcustomnamespace", "data"))
}
like image 95
Erik Dahlström Avatar answered Sep 18 '22 17:09

Erik Dahlström