How do I make javascript detect what key i'm pressing
How do I make javascript detect what key i'm pressing
window.addEventListener("keydown", function(event){
if (event.code == "yourKeyCode"){
console.log("Key pressed!");
//something
}
});"yourKeyCode" you can check in this example (or find another on your language).
That's what I found online when I searched for it and I didn't understand so can you explain how it works
"window" is JS element which is all your browser page. "addEventListener" listens all events "keydown" (press key on keyboard) on this element (when mouse cursor is in the page). Then it runs function. In function we check code of this key (event.code) and if it`s true we do code in {}.
For example key Z has code "KeyZ", shift has code "ShiftRight" and "ShiftLeft". You should replace string "yourKeyCode" with needed you key code.
If you need check press key on concret element (some input, for example), you can use
yourElement.addEventListener("keydown", function..."yourElement" you can get with
var yourElement = document.querySelector(".class-name")"class -name" is name of your element class, or you can use # for get element by id (querySelector("#yourId");)
Ohhhhhh at first I just put "r" like this
window.addEventListener("keydown", function(event){
if (event.code == "r"){
location.href = mw.util.getUrl(mw.config.get("wgPageName"), {action: "raw"});
}
});Also thank you
No, you should use "KeyR" for "r".
What do you think?