Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about Handling An _ESC_ Keypress Event In JS.
Table of Contents
Handling An _ESC_ Keypress Event In JS
Handling an “ESC” keypress event in JavaScript can be done using the keydown
or keyup
event on the document
object. The keydown
event is triggered when a key is first pressed down, while the keyup
event is triggered when a key is released.
To handle the “ESC” keypress event, you can attach an event listener to the document
object and check if the event’s key
or code
property is equal to “Escape”. Here is an example of how you can handle the “ESC” keypress event using the keydown
event:
Code For ESC Keypress Event
document.addEventListener("keydown", function(event) {
if (event.key === "Escape" || event.code === "Escape") {
// Your code here
console.log("ESC key pressed");
}
});
You can also use keyup
event instead of keydown
and the logic remains the same.
document.addEventListener("keyup", function(event) {
if (event.key === "Escape" || event.code === "Escape") {
// Your code here
console.log("ESC key pressed");
}
});
You can also use keycode
property of the event in older browsers where key
and code
properties are not supported.
document.addEventListener("keydown", function(event) {
if (event.keyCode === 27) {
// Your code here
console.log("ESC key pressed");
}
});
Explanation
In the above example, the function passed to the addEventListener
method will be called whenever the “ESC” key is pressed. Inside the function, you can add any code that you want to execute when the “ESC” key is pressed, such as closing a modal window, canceling a form submission, etc.
It’s worth noting that the above examples are for handling the keypress event on the entire page, if you want to handle the keypress event on a specific element, you can attach an event listener to that element instead of document
.
Conclusion
In conclusion, handling an “ESC” keypress event in JavaScript can be done by attaching an event listener to the document
object, listening for the keydown
or keyup
event, and checking if the event’s key
, code
or keycode
property is equal to “Escape”.
If you liked this post Handling An _ESC_ Keypress Event In JS, then please share this with your friends and make sure to bookmark this website for more awesome content.