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.
eventListener listen for clicks on said anchor link. For example:
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
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:
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!