简体   繁体   中英

Keydown event does not fire a function

I've made a simple code which should change visibility of box while certain key is pressed,but something is wrong because whichever button will be pressed it always says it's wrong.

This should work only while "f" key is pressed,right now it doesn't work at all...

const brick = document.querySelector('.brick');

window.addEventListener('keydown',function(e)
{ 
    e.preventDefault();

    if(e.keycode == 70)
    {
        let x = event.keyCode;
        console.log(x);
        brick.style.visibility = "visible";    
    } else {
        let x = e.keyCode;
        console.log(x);
        console.log("You've pressed wrong button")
        brick.style.visibility ="hidden";
    }

});

Code is Here

I know i can use jquery but i would like to do this in pure JS

Greets

Slight syntax error:

if(e.keycode == 70)

should be:

if(e.keyCode == 70)

Notice the capital C.

This may helpful . After run the code press key "F" in the keyboard to see the red div

 const brick = document.querySelector('.brick'); window.addEventListener('keydown',function(e) { e.preventDefault(); let x = e.keyCode; if(x == 70) { //console.log(x); brick.style.visibility = "visible"; } else { //console.log(x); //console.log("You've pressed wrong button") brick.style.visibility ="hidden"; } }); 
 .brick { width:100px; height:100px; visibility: hidden; background-color: red; display:block; } 
  <div class="brick" > </div> 

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