0

I try to add event listener function, but for some reason it fails. See example:

<!DOCTYPE html>
<html>
    <head>
        <script>    
        function loaded(){
                document.getElementById("first").addEventListener("click", showPopup());

        }


        function showPopup(){
            alert('hello');
        }


</script>
    </head>
    <body onload="loaded()">        
        <div id="first"> 
            click me !!!
        </div>
    </body>
</html>

Clicking on the "click me!!!" text do nothing, furthermore showPopup() function fires once.

I deeply apologize for this trivial question, but I am spending too much time to see the mistake.

Thanx a lot

lyborko
  • 2,571
  • 3
  • 26
  • 54

2 Answers2

1

You should not execute the function, but pass it:

Instead of this:

document.getElementById("first").addEventListener("click", showPopup());

do:

document.getElementById("first").addEventListener("click", showPopup);
trincot
  • 317,000
  • 35
  • 244
  • 286
1

Try this

document.getElementById("first").addEventListener("click", showPopup);
  • removed () in showPopup

`

Dave
  • 2,764
  • 2
  • 15
  • 27