简体   繁体   中英

How to detect when a key is pressed in JS?

I want to know how to make a function run when a specific key is pressed in JavaScript. For Example, when I press enter, it will run function that does:

alert("You pressed enter");

Do you use addEventListener or what? Thank you!

Yes - jsfiddle

document.addEventListener('keydown',function(e){
    var key = e.keyCode || e.which; // some browsers using keyCode,some which
    if(key == 13){
         alert('you press enter on the page');   
    }
});

You can indeed use addEventListener, but use (for example jQuery) to prevent errors on different browsers.

For a list of keyCodes: http://www.javascripter.net/faq/keycodes.htm

$(window).keydown(function(event) {
    if (event.which === 13) {
        alert("You pressed enter");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM