sash84
sash84

Reputation: 105

keypress event activates before keying and only once

I'm a newbie to javascript and just wrote a script which looks for keypress event and show the code .

<!DOCTYPE html>
<html>
    <head>
        <script>
            window.addEventListener("keypress",func(Event));
            function func(event){
                var x = event.keyCode ;
                alert("You have pressed : " + x );
            }
        </script>
    </head>
    <body>Key Press Demo</body>
</html>

The function however is being called during window load and shows undefined and it is not working continously. Let me know where I'm going wrong.

Upvotes: 0

Views: 54

Answers (1)

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

The second parameter for addEventListener expects a reference to a callback function for the event, instead you are directly calling the function which is why it executes right away. Instead just pass func

window.addEventListener("keypress", func);

Upvotes: 1

Related Questions