Eseirt
Eseirt

Reputation: 261

Click event fires on document load Tampermonkey

I'm writing a Tampermonkey script that adds a button to a page and then adds an onClick event to that button. I have the button on the page where I want it, but when I try to attach a click event using "addEventListener" as recommended in related questions about click events in user scripts, the event handler fires on page load and not when the button clicks.

var testbutton = document.createElement("button");
testbutton.addEventListener('click', alert("Working"), false);
testbutton.id = "testbutton";
testbutton.innerHTML = "This is a button";

testElement.appendChild(testbutton);

Basically, when the page loads the "Working" alert fires, but then not when I click the button. I get no console feedback either. What am I missing?

Upvotes: 3

Views: 4286

Answers (1)

adeneo
adeneo

Reputation: 318182

That's because you're calling alert on pageload, not on click, you probably wanted an anonymous function as well

var testbutton = document.createElement("button");

testbutton.addEventListener('click', function() {
    alert("Working");
}, false);

testbutton.id = "testbutton";
testbutton.innerHTML = "This is a button";

testElement.appendChild(testbutton);

Whenever you add the parentheses to a function, it's called immediately, to call the function on an event, you just want to reference it, here are some examples

addEventListener('click', alert("Working"), false); // called immediately

addEventListener('click', alert, false);            // called on click

addEventListener('click', function() {}, false);    // called on click

addEventListener('click', function() {
   alert();
}, false);    // called on click

Upvotes: 6

Related Questions