[Solved] – JavaScript – How can we detect escape key press with pure JS or jQuery?

How can we detect escape key press with pure JS or jQuery?

Asked on October 18, 2018 in Javascript.
Add Comment


  • 2 Answer(s)

       The keyup event occurs when a keyboard key is released.The keyup() method triggers the keyup event, or attaches a function to run when a keyup event occurs.
    $(document).keyup(function(e)

    {
    if (e.keyCode == 27) { // escape key maps to keycode 27
    // <DO YOUR WORK HERE>
    }
    });

         Trigger the keyup event for the selected elements.Attach a function to the keyup event.keyup method is defined with a method and a function over it and the letter e and with keycode of the value 27 if the keycode = 27 it is the escape key value and is says that do your work.

    Answered on October 18, 2018.
    Add Comment

      The Escape key is used to display the key in the webpage as the onkeydown is the object defined in it and a function of event (evt) is used here

    document.onkeydown = function(evt) {
    evt = evt || window.event;
    var isEscape = false;

    if (“key” in evt)

    {
    isEscape = (evt.key == “Escape” || evt.key == “Esc”);
    }

    else

    {
    isEscape = (evt.keyCode == 27);
    }
    if (isEscape) {
    alert(“Escape”);
    }
    };

       Where event of the function is equal then the Escape key is set to false initially and the if key in event is set to escape or the Escape key is set with the keycode and is set directly with key it displays a alert message on the top.

    Answered on October 18, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.