Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 537
Wolfie Avatar asked Feb 13 '26 17:02

Wolfie


1 Answers

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>
like image 51
epascarello Avatar answered Feb 15 '26 05:02

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!