Keypress Event Does Not Work in Chrome For Escape Key

Keypress Event Does Not Work in Chrome For Escape Key

It is very common these days to allow your web page to respond to your website users using key shortcuts. Recently I was working on a project to display an overlay on top of a page (lightbox style), and the third party that I used is called iBox. It worked great and very light weight, but it had a problem with “Escape” key to get user back to the web page, i.e., hide the overlay. This is what the coder used (slightly modified version):
    window.addEventListener('keypress', function(e){
        if (e.keyCode == (window.event ? 27 : e.DOM_VK_ESCAPE)) {
            Overlay.hide();
        }
    });
The code is simple, We just want when user presses the “Escape” key on the keyboard to hide the overlay that was displayed on the screen. This worked in latest FF, but not in Chrome. And looks like it does not work for all the keys on the first line of my keyboard (I use Mac keyboard, not sure whether this is the cause of the issue or not). In order to capture the this event, I need to use “keydown” instead:
    window.addEventListener('keydown', function(e){
        if (e.keyCode == (window.event ? 27 : e.DOM_VK_ESCAPE)) {
            Overlay.hide();
        }
    });
Problem solved, but not an obvious one. Hope this helps.

Leave a Reply

Your email address will not be published.

My new Snowflake Blog is now live. I will not be updating this blog anymore but will continue with new contents in the Snowflake world!