Search code examples
javascripthtmlkeypress

How do I use JavaScript to respond to a key press?


I'm sorry if this is a general question but what block of code should I use to make javascript or html respond to a key press or key event? Any way to do it is ok but I just want to make my website more interactive. Thank You!

And don't go around saying that this is a copy of some other question. It is not. I don't know why anyone would think that, too because the "original" question is asking "how do I know if a key is pressed". I am asking how do I make my website respond to a key press. And to the comment below, I have been searching this stuff up but isn't that what this website is for? I don't have a P.H.D in computer science and I'm just asking questions so I can understand these computer languages a little better but every time I ask a question everyone gets really mad at me because somehow a question about javascript is a lot like a fancy jquery command. But back on topic I am just looking for ways that my website can react to a key press. Once again, Thank You!


Solution

  • There are a lot of ways to do this, most people use jQuery but below is an example with raw JavaScript.

    You can usually listen to either key down or key up. In most cases, you won't want code to execute until the key is released (key up).

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    function makeUpperCase() {
        var x = document.getElementById("element-id");
        x.value = x.value.toUpperCase();
    }
    </script>
    </head>
    <body>
    
    <p>When you enter a character in this field, it will be made uppercase on key up.</p>
    Enter your name: <input type="text" id="element-id" onkeyup="makeUpperCase()">
    
    </body>
    </html>