Hide or Close Div Using Escape Key JavaScript | jQuery | AngularJS

Esc key on our keyboard can be useful even in Web pages and applications. We can use Esc key to close dialogue boxes or any custom popup modals. Here we will discuss even handling on ESC key press in which we can fire any event we want.

Let’s handle ESC key press events in Javascript, jQuery, and AngularJS.

 

 

In Javascript, we will bind the OnKeyUp event on the window object. In that even we will add a condition if KeyCode is 27 which is of ESC key press, In that event, we will hide the element having an ID

var boxid = "MyBoxID";
 window.onkeyup = function (event) {
  if (event.keyCode == 27) {
    document.getElementById(boxid).style.visibility="hidden";
  }
 }

 

In jQuery, we will use the KeyDown event to bind on the document object.

var elem = "#elementID"; 
$( document ).on( 'keydown', function ( e ) {
    if ( e.keyCode === 27 ) { // ESC
        $( elem ).hide();
    }
});

In AngularJS we need to add a directive which will bind a keyDown event to the body tag

    angular.module('app').directive('body', function() {
        return{
            restrict : "E",
            link: function(scope, elm, attrs) {
                elm.bind('keydown', function(evt) {           
                      if (evt.which == 27) {
                        //Change Boolean Value Here or Any Other Login
                        $scope.isModalOpen = false;
                        console.log(evt.which);               
                      }
                });
            }
        }
    })

 

Subscribe
Notify of
guest
2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Vitolker

Thanks for the info.

Asim

Hi,

Thanks bro, It works