0

I want to execute a JS code when user presses ESC key. Please help me how can I do this? My current code is not working. I don't know where I'm doing wrong? I'm just a beginner so please help me out..

function hideModalKeyPress(e)
{
 if(e.keyCode == 27)
 {
  document.getElementsByClassName('modalOverlay')[0].style.visibility = "hidden";
 }
}
.modalOverlay
{
  width: 200px;
  height: 200px;
  opacity: 0.8;
  background-color: black;
  visibility: visible;
}
<div class="modalOverlay" onkeydown="hideModalKeyPress(e);">Press ESC to hide me.</div>

/*
 * I want to set the div's visibility to hidden
 * when user presses ESC key
*/
uraimo
  • 19,081
  • 8
  • 48
  • 55
Rohit Kumar
  • 2,048
  • 1
  • 14
  • 28

2 Answers2

0

You could use jQuery and do the following:

$(document).keyup(function(e) {
  if (e.keyCode == 27) {
      $(".modalOverlay").css('visibility', 'hidden');
  }   
});

JSFiddle

Or in pure JavaScript:

document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        document.getElementById("modal").style.visibility = "hidden";
    }
};

JSFiddle

Boxiom
  • 2,245
  • 6
  • 40
  • 51
  • can you provide a pure JS format version of this? It will be helpful. – Rohit Kumar Jun 03 '15 at 18:42
  • Added pure JS as well :) Keep in mind that you need to set the div's ID to `modal`. – Boxiom Jun 03 '15 at 18:59
  • can you explain a little how the above code works?? Actually I didn't understand the 2nd line - evt = evt || window.event; – Rohit Kumar Jun 03 '15 at 19:06
  • You can find a good explanation here: http://stackoverflow.com/questions/3493033/what-is-the-meaning-of-this-var-evt-eventwindow-event :) – Boxiom Jun 03 '15 at 19:14
0

This worked for me:

document.addEventListener("keydown", hideModalKeyPress, false);
function hideModalKeyPress(e) {
    if(e.keyCode === 27)
    {
        document.getElementsByClassName('modalOverlay')[0].style.visibility = "hidden";
    }
}

Here is the working jsfiddle: https://jsfiddle.net/7jrfrz26/

Arathi Sreekumar
  • 2,544
  • 1
  • 17
  • 28