I am trying to have a common click handler for all the elements I am appending to a SVG canvas. But I cannot delegate the handler to the newly created elements.
This is the code I have tried to delegate, but no luck
$("#floor").on('click','.drawnLine', function() {
//#floor is the SVG Element
//.drawnLine is the <line> element that is added dynamically
console.log($(this).data('index'));
});
Update:
On the jQuery manual of .on()
it is mentioned that
Note: Delegated events do not work for SVG.
So now the question is any other workaround for this problem?
TL/DR: Attach the event listener to a non-SVG parent element.
The note in the jQuery docs is somewhat misleading.
It should probably be...
jQuery's event delegation does not work when the event listener is attached to an SVG element; however, if you instead attach the listener to a non-SVG parent of the SVG, event propagation works as expected and any selectors that match SVG elements will indeed trigger your event handler function.
Attaching the listener to the SVG element will not work:
But attaching it to a parent element will work:
Note: one quirk I've noticed is that if the event target is an SVG element, the event won't bubble up all the way to
document.body
on iOS. So if you want iOS users to be able to trigger your handler function you'll need to attach your event listener to some element in between (such as thediv
element your SVG resides in).When jQuery fails with SVG you can use vanilla js. Fortunately every browser that supports svg also supports event listeners. The pure js delegated event is not so ugly:
But you can also create your own function to delegate your events more cleanly.