skip to Main Content

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


  1. 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>
    
    Login or Signup to reply.
  2. 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.

    document.querySelector('svg').addEventListener('click', (e) => {
      if (e.target.tagName === 'rect')
        console.log(e.target.id);
    });
    <svg>
      <rect id="red" width="20" height="20" fill="red"/>
      <rect id="blue" width="20" height="20" fill="blue" x="20" y="20" />
    </svg>
    Login or Signup to reply.
  3. 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.

    function setupSvgListeners(){
      document.querySelector('svg').addEventListener('click', (event)=>{
        on(event.target.id);
      }
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search