Search code examples
javascripthtmlonclickonclicklistenerfigure

How to set on click listener for figure tag?


I have the following simple html doc:

<!DOCTYPE html>
<html>
<head>
</head>

<body>
    <figure>
        <object class="" type="image/svg+xml" data="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350"></object>
    </figure>
</body>

<script>
    var figures = document.querySelectorAll('figure')
    for (let figure of figures) {
        figure.addEventListener("click", function () {
            console.log("hello")
        })
    }
</script>

</html>

However, nothing happens when I click on the image. Is it possible to set an on click listener for a figure tag, and if not, what are the alternatives I can use?


Solution

  • The problem is not the figure but the object tag. This tag runs in a nested context that doesn't propagate events back to the parent; therefore, when you click on the figure loaded by the object it doesn't fire back from the embedded object never reaching the click on your figure.

    The object tag is meant to run embedded applications (flash apps back in the day) so it has an abnormal behaviour similar to iframe, there are a lot of security concerns.

    You can use an img to load your svg instead of an object, it will load the same way and this does fire the event back to the parent, hence, triggering the click on the parent figure.

    <figure>
      <img width="100" height="100" src="./path/to/img.svg">
    </figure>
    

    Bellow there is a snippet showing the different behaviour when using object and img to load an image, the second triggers the click.

    var figures = document.querySelectorAll('figure')
    for (let figure of figures) {
      figure.addEventListener("click", function() {
        console.log("hello")
      })
    }
    <figure>
      <figcaption>I'm an object and I don't propagate events back to my parent</figcaption>
      <object width="100" height="100" type="image/svg+xml" data="https://upload.wikimedia.org/wikipedia/commons/f/fd/Ghostscript_Tiger.svg"></object>
    </figure>
    
    <figure>
      <figcaption>I'm an img and I propagate events back to my parent</figcaption>
      <img width="100" height="100" src="https://upload.wikimedia.org/wikipedia/commons/f/fd/Ghostscript_Tiger.svg">
    </figure>