Preventing SVG from becoming the event.target

Schalk Neethling
2 min readOct 11, 2018

--

“selective focus photography of X logo” by David Paschke on Unsplash

SVG or Scalable Vector Graphics, is undoubtedly one of the best technologies that has received wide user agent support over the last couple of years. It allows us to have high-res images for a fraction of the byte size of a PNG, GIF or JPEG.

We have almost full control over it via CSS as well as JavaScript. Sometimes though, you really want the SVG to look pretty, and not get in the way. The scenario I am referring to, is when you use an SVG inside an anchor link, and then have an eventListener listen for clicks on said anchor link. For example:

In you JavaScript you then might have an eventHandler setup as follows:

On the surface this look all good, but there is a catch. When a user clicks on the above defined link, dependent on the precise x/y coordinates where the mouse click happened, the event.target might be the SVG or even the path inside. 😱

This means that sometimes clicks on the link will never be handled as the conditional will return false. Now, you might say: “Just be less restrictive and remove the conditional”. To which I would counter: “Well, what if you depended on an attribute set on the anchor tag, such as a data attribute?”.

Thankfully there is a way to have your cake and eat it too. Enter, the CSS pointer-events property. To quote the MDN Web Docs documentation page:

The pointer-events CSS property specifies under what circumstances (if any) a particular graphic element can become the target of mouse events.

The Resolution

So, in order to prevent the SVG or the path being returned as the event.target we want to ensure that it can never become the target of a mouse event.

For our scenario then, we know the SVG is wrapped in an anchor tag with a class of local-anchor and we know that the SVG element inside it, will always have at least a class of icon. We can therefore add the following CSS to our codebase:

And there it is, problem solved. And the browser support for basic usage(which is all we need here) is really, really good.

I hope you enjoyed this post and found it useful. I look forward to hearing your comments. Happy Web Making!

--

--

Schalk Neethling

I write about mental health, addiction, sober living, living your best life through an active lifestyle and a whole food plant-based diet. Psychedelic curios :)