Collin Willson
Collin Willson

Reputation: 9

Keypress trigger a function if specific pressed

I'm at my wits end on this. I have looked everywhere and can't find it. I want to trigger a function by pressing the letter "p" I tried a few methods but they didn't work. I am also not using jQuery.

Here is my code here:

//If key p is pressed, then trigger the stopsound function

function checkKey(p) {
    stopmusic
}
document.addEventListener("keypress", stopmusic);

I want it to detect the letter p and trigger the function "stopmusic". It has an event listener but it picks up all keys. I want to define it but cannot find it when I search it up. Thank you

Upvotes: 0

Views: 425

Answers (1)

adeneo
adeneo

Reputation: 318182

The p key would be 112, so just check the event for that

function checkKey(e) {
    var key = e.which || e.keyCode;
    if (key === 112) stopmusic();
}

document.addEventListener("keypress", checkKey);

Upvotes: 1

Related Questions