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?
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"))
}
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