AddEventListener DOMContentLoaded not working

I am trying to create a simple script that will add a listener to a button to call a function that displays a warning when the page is fully loaded.

script must be implemented in Chrome extension

I am 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, as well as the first showalert (); does not start.

I’m probably stupid here, but I don’t understand why this is not working. Any help would be greatly appreciated!

JSfiddle: http://jsfiddle.net/bunker1/fcrwt/1/

+5
source share
1 answer

Found a mistake, I was stupid.

The code worked after JSfiddle did not pack and delete () from the second argument.

correct code:

    document.addEventListener('DOMContentLoaded', function () {
         document.querySelector('button').addEventListener('click', showalert, false);
    }, false);

    function showalert() {
        alert("you just pressed the button");
    }
+4
source

All Articles