tobbe
tobbe

Reputation: 1807

addEventListener(click) fires on page load

I am probably ... right now, but why is this code logging hello x2 when my page loads, and nothing when clicking an LI-element? It should log the clicked elements name. If I change "hello" to e.target, it logs HTMLDocument!

<!DOCTYPE html>
<html>
    <head>
        
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        
        <script type="text/javascript">
            
            window.onload = function(){
                var list = document.getElementById("listan");
                
                list.addEventListener("touchstart", elementClicked(event), false);
                list.addEventListener("click", elementClicked(event), false);
            }
            
            function elementClicked(e) {
                
                console.log("hello");
                
                if(e.target && e.target.nodeName == "LI") {
                
                    console.log(e.target.nodeName);
                }
                
            }
            
        </script>
        
        
        <style>
        
            * {
                list-style: none;
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            
            li {
                width: 90%;
                background: darkblue;
                color: #eee;
                margin: 10px auto;
                padding: 15px;
                border: 1px solid black;
                text-align: center;
                font-family: calibri;
                cursor: pointer;
            }
            ul {
                background: green;
                padding: 10% 0;
            }
            
        </style>
        
    </head>
    <body>
        <ul id="listan">
            <li>apa</li>
            <li>häst</li>
            <li>ko</li>
            <li>elefant</li>
            <li>lejon</li>
            <li>zebra</li>
            <li>myrslok</li>
            <li>grävling</li>
        </ul>
    </body>
</html>

Upvotes: 0

Views: 522

Answers (1)

Xymostech
Xymostech

Reputation: 9850

For these:

list.addEventListener("touchstart", elementClicked(event), false);
list.addEventListener("click", elementClicked(event), false);

you want to be passing in the actual function, elementClicked, so just use:

list.addEventListener("touchstart", elementClicked, false);
list.addEventListener("click", elementClicked, false);

Upvotes: 4

Related Questions