Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

userscript addEventListener seemingly not attaching to element

I’m trying to attach an onclick event listener to an existing element (notably not a button with a form, it’s a simple div) on a webpage through a userscript. However, it appears that, even though to my knowledge adding an event listener in an anonymous function shouldn’t run afoul of timeout rules for the userscript existing, it doesn’t attach anything (or, possibly, it does, but then the userscript times out and the anonymous function stops existing, causing the event listener to fall off. Am I misunderstanding something fundamental about the scope of user scripts?

I’ve tried attaching it to the button in the following manner. This is not caused by some obscure race condition with re-binding outerHTML to itself, because even without that line the event listener is not added.

var button = document.getElementById("button");
button.outerHTML = button.outerHTML; // removes all existing event listeners on the element
button.addEventListener("click", function() {
  window.alert("ping"); // or any other function body
}, false);

Firefox 112.0.2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It does not work because when you do button.outerHTML = button.outerHTML; the button you originally referenced is no longer the button in the DOM. You are replacing that button with a new button.

You would need to select the button again.

var button = document.getElementById("button");
button.outerHTML = button.outerHTML; // removes all existing event 

button = document.getElementById("button");
button.addEventListener("click", function() {
  window.alert("ping"); 
}, false);
<button id="button">click</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading