简体   繁体   中英

Check if any key is pressed Javascript without a form

if (any key is pressed){
Hide a div.
}

I am wondering if there is an easy way to detect if any key is pressed without an input.

document.onkeypress=function(e){
    //do the required work
}

Attach the keypress event in body or other element you want. Something like

<body onkeypress="myFunction()">

Or

document.body.addEventListener('keypress', myFunction);

Funciton Definition

function myFunction(){
     //do what you want after key is pressed
}

you didnt tag it jQuery, but if you are willing to try a jQUery solution check This Page

take note that jQuery is simply a huge javascript extension file which is available for free on their website.

An example of attaching a keypress event handler with addEventListener to window , and how to be sure to clean it up on unload with removeEventListener

CSS

.hideMe {
    display:none;
}

HTML

<div id="hideOnKeyPress">Now you see me.</div>

Javascript

var hideOnKeyPress = document.getElementById('hideOnKeyPress');

function pressed() {
    hideOnKeyPress.classList.add('hideMe');
}

function unload() {
    window.removeEventListener('keypress', pressed, false);
    window.removeEventListener('unload', unload, false);
}

window.addEventListener('keypress', pressed, false);
window.addEventListener('unload', unload, false);

On jsFiddle

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