2

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!

1
  • Yes addEventListener we use. Can we see your code so far? Commented Apr 27, 2013 at 22:53

2 Answers 2

4

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');   
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

var key = e.keyCode || e.which
-1

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");
    }
});

1 Comment

keyCode is not standardized by jQuery, event.which is...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.