Search code examples
javascriptsvgonclick

Looking for a way to call a Javascript function when a mouse event occurs for any path in an SVG


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.


Solution

  • 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:

    <script>
    function onSvg(event) {
      on(event.target.id);
    }
    </script>
    <svg onClick="onSvg" ></svg>