3

I would like to know how I use onkeydown and onkeyup event in javscript correctly with an event listener. I want the event to listen when you just press in the website, not in a text field.

I don't know exactly how the script would look like but hopefully you understand what I want to do. I figured the code would look something like this:

document.addEventListener('keydown', 'keyup', function(event) {
if(event.keyCode == 65){
    gas1();
}});

Sorry for being so unclear, trying my best to explain

3

5 Answers 5

5

Look an example I prepared in jsfiddle:

document.addEventListener('keydown', function(event) {
    console.log(event.key);
});

Simply add a listener to the whole document and check for the "key" in the event object you receive in the callback

keydown event test

Sign up to request clarification or add additional context in comments.

Comments

1

Try Implementing this

document.onkeydown = function(event) {
    if(event.keyCode == 65){
        gas1();
    }
}
document.onkeyup = function(event) {
    if(event.keyCode == 65){
        gas1();
    }
}

But if you want to call a function gas1() only once on keypress just use keydown only.

Comments

1

You can't aggregate two events on a single document.addEventListener. The first parameter is the name of the event, and the second a listener function called when it's fired.

Create two handlers, one for keyup and one for keydown, or use just keypress instead for this.

Reference: http://www.w3schools.com/jsref/met_document_addeventlistener.asp

Comments

1

You can use below code for checking KeyUp and KeyDown press on HTML page.

Note :Arrow keys are only triggered by onkeydown.

$(document).ready(function() {
    document.onkeydown = function(event) {
    if(event.keyCode=="38")
	    console.log("Up key pressed");
    else if(event.keyCode=="40")
        console.log("Down key pressed");
   };		
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Above code is tested on system working fine.

Note :Try testing while your focus should be in Result area to print output on console.

Comments

0
function defw(){
     for(var i =0; i < 10; i+= 1) {
      var div = document.createElement('div');
      document.getElementsByTagName('section')[0].appendChild(div);
      }
 }

document.addEventListener('keydown', function(event) {
    var ekey = event.keyCode
    if( 69 === ekey ) {
       defw();
    }
});

This example is to make 10 DIVS calling the function defw()
1. SAVE the event.keyCode in a variable
2. THe value 69 is the keyboard letter e in your KEYBOARD

HERE IS THE LINK codepen.io

Comments

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.