Search code examples
debuggingevent-handlingkeyboard-eventssilentdom-events

How do I use an anonymous function as an event handler for a DOM element in JavaScript?


I am writing a keypress event handler using an anonymous function expression:

btnuser.onkeypress = function (event) {
                       alert("Hello");
                     };

But it is failing silently.

Can anyone help me see what's wrong with this code?


Solution

  • Assuming txtuser is an ID attribute value, the syntax should be as follows:

    document.getElementById("txtuser")
    

    rather than

    txtuser
    

    Also, make sure of the following:

    • The script tag is defined after the element in question in the source

    • The browser supports the onkeypress event for the key in question

    References