javascript - Click event fires on document load Tampermonkey - Stack Overflow

I'm writing a Tampermonkey script that adds a button to a page and then adds an onClick event to t

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 remended 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?

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 remended 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?

Share Improve this question asked Mar 30, 2015 at 14:11 EseirtEseirt 2613 silver badges11 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 6

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745275187a4619996.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信