I have an SVG with thousands of paths in this format:
<path id="c02130" d="m256.29 573.18-0.78515 1.1758h1.1777v-0.78516zm0.39258-1...
<title>Ketchikan Gateway, AK</title>
</path>
I need to call a Javascript function whenever a mouse event occurs for the path. Currently, I do this on click and it works well:
<path id="c02130" onclick="on('c021830')" d="m256.29 573.18-0.78515 1.1758h1.1777v-...
<title>Ketchikan Gateway, AK</title>
</path>
The on() function fetches text from the server using AJAX and writes it to a <div> area.
I’m wondering if there’s a better way that doesn’t require adding an onclick to each path, given that all paths will be treated the same way – passing their id to a Javascript function.
3
Answers
Yes, there is a better way:
add the onClick event listener, to the svg, and use the
event.target
to see where is the event comes from something like this:Try and avoid inline events, the more modern way is to use
addEventListener
.Note: because events bubble, you don’t need to add the event to every element, add to the parent and do some basic checking there.
eg. Below I’ve created two Rect’s with ID’s, I then check to make sure what was click was a Rect, and then console.log the ID.
If your "on" function is the same for any svg in the system, i.e., doesn’t depend on context, you could setup a universal listener. If it’s context specific, then follow Peter’s advice.