What is the best (cross browser) approach to get the attribute id
(or basically any attribute that helps me identifying the Element on which the event happened) within an event handling function (e.g. click callback function) of snap.svg /
Here is some code. What I have tried seems to work in latest Chrome and FF, but I wonder if there is a better approach.
//add an Element, set id
var mySvg = Snap('#mySvg');
var myRect = mySvg.rect(10,10,200,100);
myRect.attr({id:'myId'});
//register click callback
myRect.click(clickCallback);
//click callback
var clickCallback = function(event) {
// how do I get the id of the clicked element?
// is this cross browser valid?
var id = event.target.attributes.id.nodeValue;
};
What is the best (cross browser) approach to get the attribute id
(or basically any attribute that helps me identifying the Element on which the event happened) within an event handling function (e.g. click callback function) of snap.svg http://snapsvg.io/
Here is some code. What I have tried seems to work in latest Chrome and FF, but I wonder if there is a better approach.
//add an Element, set id
var mySvg = Snap('#mySvg');
var myRect = mySvg.rect(10,10,200,100);
myRect.attr({id:'myId'});
//register click callback
myRect.click(clickCallback);
//click callback
var clickCallback = function(event) {
// how do I get the id of the clicked element?
// is this cross browser valid?
var id = event.target.attributes.id.nodeValue;
};
Share
Improve this question
asked Jan 24, 2014 at 16:13
mwallischmwallisch
1,8192 gold badges22 silver badges30 bronze badges
0
1 Answer
Reset to default 5I think there's an issue with the current version of Snap and id, which is fixed in next release (0.2 which may be current by now) https://github./adobe-webplatform/Snap.svg/issues/166 so worth a read at some point.
However, I typically don't use an id like that for these cases, I would use 'this'. So with a handler, it can look something like...
var mySvg = Snap(400, 620);
var myRect = mySvg.rect(10,10,200,100);
var clickCallback = function(event) {
this.attr({ fill: 'blue' });
};
myRect.click(clickCallback);
jsfiddle here http://jsfiddle/qgTdF/2/
This solution may work for you, and be preferable, but it depends ultimately if you need to do something else (in which case maybe post another question with the specific issue). It may also be worth trying the latest version (I think 0.2), if you need to fiddle a bit and specifically use the id.