Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener DOMContentLoaded not working

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.net/bunker1/fcrwt/1/

like image 635
Bunker Avatar asked Oct 04 '22 17:10

Bunker


1 Answers

Found 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");
    }
like image 69
Bunker Avatar answered Oct 15 '22 20:10

Bunker