I'm trying to create a simple script that will add a listener to a button to trigger a function that displays an alert when the page is fully loaded.
The script is to be implemented in a Chrome Extension
I'm using the following code:
document.addEventListener('DOMContentLoaded', function () {
showalert();
document.querySelector('button').addEventListener('click', showalert());
});
function showalert() {
alert("you just pressed the button");
}
And my HTML
<button id="button">button</button>
The listener is never added to the button, also the first showalert(); is not fired.
I'm probably being stupid here, but I'm failing to see why this is not working. Any help would be greatly appreciated!
JSfiddle: /
I'm trying to create a simple script that will add a listener to a button to trigger a function that displays an alert when the page is fully loaded.
The script is to be implemented in a Chrome Extension
I'm using the following code:
document.addEventListener('DOMContentLoaded', function () {
showalert();
document.querySelector('button').addEventListener('click', showalert());
});
function showalert() {
alert("you just pressed the button");
}
And my HTML
<button id="button">button</button>
The listener is never added to the button, also the first showalert(); is not fired.
I'm probably being stupid here, but I'm failing to see why this is not working. Any help would be greatly appreciated!
JSfiddle: http://jsfiddle/bunker1/fcrwt/1/
Share Improve this question edited Mar 16, 2013 at 13:11 Bunker asked Mar 16, 2013 at 12:44 BunkerBunker 1,0513 gold badges14 silver badges26 bronze badges 2- 1 addEventListener takes 3 args – stark Commented Mar 16, 2013 at 13:12
- Thanks for the input, added the false argument in the fiddle without any luck unfortunately :( – Bunker Commented Mar 16, 2013 at 13:20
1 Answer
Reset to default 4Found the error, I was being stupid indeed.
The code worked after putting JSfiddle on no wrap and removing the () from the second arg.
correct code:
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', showalert, false);
}, false);
function showalert() {
alert("you just pressed the button");
}