0

I'm using an HTMLObjectElement to display svg graphics as recommended here: https://www.sitepoint.com/add-svg-to-web-page/

The problem is that in javaScript I've done something like:

const objEl = document.createElement( 'object' );
objEl.type = 'image/svg+xml';
objEl.data = 'myGraphic.svg';
objEl.onclick = () => {
  console.log( 'I was clicked' );
}

and the onclick event is never fired when I click on it with my mouse.

If I use an img rather than an object, then the click event does fire. Why doesn't the click event work for objects? How can I get click events?

Note, I have also attached objEl.onmouseover and objEl.onmouseout events and they work just fine. It is only the click events that don't work for me.

Marek Krzeminski
  • 1,308
  • 3
  • 15
  • 40
  • 1
    Have you tried using addEventListener()? – Fashim Mar 08 '18 at 03:11
  • `` element is bound to the same rules as ` – Kaiido Mar 08 '18 at 03:25
  • That's no good. Say I have 10 svg's and I want to know which svg I am clicking on. It sounds like I need to update all 10 svg's to have some sort of script inside it to report back to the parent that it was clicked. The parent would then also have to listen to these messages.... I'm going to see if there is any other way of using svg's that doesn't require me to edit the svg's to be notified when they are clicked. I have way to many svg's to edit this way. – Marek Krzeminski Mar 08 '18 at 13:42
  • @MarekKnows.com You can also try as proposed in the dupe: access all the inner docs from your main doc and attach your click events from there. HTMLObjectElement even offers a `getSVGDocument` method, but this technique is bound to same origin policies. – Kaiido Mar 09 '18 at 00:39

0 Answers0