How to click on a part of an SVG within a website with Javascript?

Viewed 859

Javascript provides a method called click().

This works for example:

<a id="a" href="index.htm">Click here</a>

and

document.getElementById("a").click();

But what about SVG-Elements?

<svg>
  <g id="a" .....></g>
</svg>

This won't work:

document.getElementById("a").click();

I can successfully select the g-Tag, but it has no click method:

document.getElementById(...).click is not a function

Is it somehow possible to click an element within an SVG-Tag with Javascript?

4 Answers

You can just create and dispatch the event manually e.g.

document.getElementById("a").dispatchEvent(new Event('click'));

This is all the click() method does underneath the hood. It's just a convenience method.

This will work with any SVG element, including <g> elements.

Not entirely sure whether JavaScript has an actual click() event (I do know it can be inserted as: onclick() in HTML). jQuery has a click() event. That said, I believe you have to add an eventlistener if you are using JavaScript and no jQuery.

document.getElementById("a").addEventListener('click', function() {
     //do something
});

Have you tried the "onclick" directly on the HTML?

I know it's brutal, but did it works?

<svg>
  <g id="a" onclick="your code here"  .....></g>
</svg>
Related