How to Detect Escape Key Press with Pure Js or Jquery

How to detect escape key press with pure JS or jQuery?

Note: keyCode is becoming deprecated, use key instead.

function keyPress (e) {
if(e.key === "Escape") {
// write your logic here.
}
}

Code Snippet:

var msg = document.getElementById('state-msg');

document.body.addEventListener('keypress', function(e) {
if (e.key == "Escape") {
msg.textContent += 'Escape pressed:'
}
});
Press ESC key <span id="state-msg"></span>

Which keycode for escape key with jQuery

Try with the keyup event:

$(document).on('keyup', function(e) {
if (e.key == "Enter") $('.save').click();
if (e.key == "Escape") $('.cancel').click();
});

How to catch escape key press event inside while loop in jquery?

You need to use .setTimeout, which you can cancel with.clearTimeout once you recognise a press of the escape key. The example below works.

Let me know if you needed something else.

// Start your playLoop after document is ready$(document).ready(function() {  playLoop();});

function playLoop() {
// Append a dot so you know it's working $(".dots").append(".");
// Set a new timeout to count down playLoopCountdown = setTimeout(playLoop, 1000);
}

// Attach escape key cancel$(document).on("keyup", function(e) {
if (e.key === "Escape") {
// Stop playLoop clearTimeout(playLoopCountdown);
// Tell user the timeout has been stopped $(".dots").append("STOPPED");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>You need to click within this iframe for the escape keypress to be registered.</p><div class="dots"></div>

How to detect Esc Key Press in React and how to handle it

If you're looking for a document-level key event handling, then binding it during componentDidMount is the best way (as shown by Brad Colthurst's codepen example):

class ActionPanel extends React.Component {
constructor(props){
super(props);
this.escFunction = this.escFunction.bind(this);
}
escFunction(event){
if (event.key === "Escape") {
//Do whatever when esc is pressed
}
}
componentDidMount(){
document.addEventListener("keydown", this.escFunction, false);
}
componentWillUnmount(){
document.removeEventListener("keydown", this.escFunction, false);
}
render(){
return (
<input/>
)
}
}

Note that you should make sure to remove the key event listener on unmount to prevent potential errors and memory leaks.

EDIT: If you are using hooks, you can use this useEffect structure to produce a similar effect:

const ActionPanel = (props) => {
const escFunction = useCallback((event) => {
if (event.key === "Escape") {
//Do whatever when esc is pressed
}
}, []);

useEffect(() => {
document.addEventListener("keydown", escFunction, false);

return () => {
document.removeEventListener("keydown", escFunction, false);
};
}, []);

return (
<input />
)
};

EDIT for React 17: React changed the way that document-level event binding is handled, which may cause this implementation to stop working if at some point in the chain event.stopPropogation() is called. You can ensure that this function is called first by changing the last argument of the listener to true rather than false. If you do this and also call event.stopPropogation(), other handlers that used to be called will no longer take place, so I would suggest avoiding that call if at all possible.

JavaScript - Detect ESC key cross browser

Which version of IE do you have?
This code works for me with IE (9.01):

<!doctype html>
<html>
<head>
<title></title>
<script type="text/javascript">
window.document.onkeydown = function (e)
{
if (!e) e = event;
if (e.keyCode == 27)
alert("Hello!");
}
</script>
</head>
<body>
</body>
</html>

Check also your Doctype, your IE could use the Quirks mode, maybe.

How to detect escape key pressed when in a Youtube video?

I don't believe this is going to be possible. The Flash player captures input when it's focused - for example, if you click play in a YouTube video, then hit Ctrl-W to close the tab, it's not going to close until you click on the page outside of the video, returning focus to the browser.

Input control is effectively being passed to another process (the Flash player) while it's focused, so you're not going to be able to capture or act on input until the user explicitly returns control to the browser.

How to check if escape key has been pressed 3 times (like the trevor project website's safety)

You can accomplish this using a closure:

function createCheckKeyPressFunction()
{
let timeout;
let escTime = 0;
function checkKeyPressed(evt)
{
if (evt.key === "Escape")
{
console.log("Escape Detected");
window.clearTimeout(timeout);
escTime += 1;
timeout = window.setTimeout(()=>
{
escTime = 0;
console.log("Escape count reset to zero, due to timeout.");
}, 1000);
}
if (escTime === 3) {
let url = "https://classroom.google.com/h";
console.log(url);
window.location.replace(url);
escTime = 0;
}
}
return checkKeyPressed;
}
let checkKeyPressed = createCheckKeyPressFunction();
window.addEventListener("keydown", checkKeyPressed, false);
<p>Click to give this embedded snippet focus, and then test by hitting the ESC key.</p>


Related Topics



Leave a reply



Submit