0

I write this simple htlm file :

<svg onclick="alert('Click svg!')" style="height: 200px; width: 200px; background-color: green"></svg>
<div onclick="alert('Click div!')" style="height: 200px; width: 200px; background-color: red"></div>
<object onclick="alert('Click object!')" data="./bank.svg" type="image/svg+xml" style="height: 4308.75px; width: 7660px;"></object>

When I click on the svg, I trigger the onclick event and get the alert 'Click svg!'.

When I click on the div, I trigger the onclick event and get the alert 'Click div!'.

When I click on the object, I trigger nothing.

Am I doing something wrong?

1 Answers1

0

Looks like Object tags don't really support click events (see for example this SO question) I couldn't find a source for the comment on which elements don't support clicks but nevertheless: It's not 1990 anymore, there is no reason to still be using <object> tag for SVGs. Nowadays you can just render the SVG inline.

If you want to add click events, use a <button type="button"> to bind to the buttons click events and handle these. Don't be scared off by how a button looks by default, you can style it any way you want. Don't put click events on divs or other elements, this is not accessible.

Adding click events to divs/ spans / (anything else than a button, really) is not really good practice and should best be avoided altogether.

<button type="button" onclick="alert('clicked')">
  <svg> ... </svg>
</button>
cloned
  • 6,346
  • 4
  • 26
  • 38