Categories
Coding

Why click event not working on SVG

I created a simple menu with SVG icons and to my surprise, clicking on the icon was not taking me to the linked url.

It turned out that as SVGs are independent HTML objects, the target element is actually nested path. So, it does not match with the clicked element and thus click event listeners does not work on it.

Similarly, if you add others event listeners to the parent element of the SVG’s, it does not work.

There are multiple ways to fix this-

  1. Disable click on SVG elements by adding the CSS- pointer-events: none;

  2. Add event listener to the path element of SVG.

Problem solved.

References:

  1. https://gomakethings.com/detecting-click-events-on-svgs-with-vanilla-js-event-delegation/