Home > front end >  HTML object is blocking eventlistener
HTML object is blocking eventlistener

Time:06-13

I have imported a svg as an object in HTML:

  <object data="mySVG.svg" type="image/svg xml" id="circle">
    <img src="mySVG.svg" />
  </object>

and I am trying to set an eventlistener on the whole page:

window.addEventListener('click', function(){
   alert('Hello')
})

The problem is that the object blocks the eventlistener and when the user clicks on the image the alert is not fired. But when the user clicks anywhere else or over other elements, the alert is fired. How can I make it so the object is acting as the other elements and doesn't block the eventlistener?

I tried wait after the object is beaing loaded and then set the eventlistener but it didn't work.

If I import the SVG directly into HTML with svg tag it works, but the svg is quit big and it makes the HTML code really messy. I can't use the img tag either becuase I am also interacting with parts of the SVG with JS later.

As it can be seen in this codepen I've made: https://codepen.io/Dimertuper/pen/rNJoLrK (When you click outside the image it triggers, inside the image it doesn't)

CodePudding user response:

I think your issue here is that you're adding the event directly to the window rather than the element itself. you should be able to do the following:

 <object data="mySVG.svg" type="image/svg xml" id="circle">
    <img src="mySVG.svg" />
  </object>

and in your javascript

// capture a reference to the element we want to add the event to
const mySvgObject = document.querySelector("#circle")

// add the event
mySvgObject.addEventListener("click", function() {
        alert("Hello")
})

Here's a codepen as an example in case it is needed.

CodePudding user response:

Try this:-

document.addEventListener('click', function(){ alert('Hello') })

There is a difference between 'document' and 'window'. Document is used to access any html element on the web page, whereas window represents the frame of the browser. So when you click on the button (html element) by using 'window', it doesn't work. You can check the differences between document and window here: https://www.geeksforgeeks.org/differences-between-document-and-window-objects/

  • Related