Search code examples
javascriptjqueryhtmlfullscreenkeycode

How to add escape key to close mobile navigation


Basically I'm using a hamburger menu (full screen overlay) on desktop and would like to assign the 'Escape' key so users are able to close the menu.

Currently this is my mark-up

            <div id="myNav" class="overlay">
            <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
            <div class="overlay-content">
                <a href="#">About</a>
                <a href="#">Services</a>
                <a href="#">Clients</a>
                <a href="#">Contact</a>
            </div>
        </div>
        <div><span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span></div>

And this is the JS I have alongside it - which works fine if a user was to click the close icon

function openNav() {
    document.getElementById("myNav").style.width = "100%";
}

function closeNav() {
    document.getElementById("myNav").style.width = "0%";
}

Because I am using a style width 100% to show the navigation instead of assigning it a class I have come a little unstuck.

Any help would be much appreciated!

Thanks in advance


Solution

  • You have to add an keypress or keyup event listener to your document and check if the pressed key is esc (char code 27).

    This is what it'd look like:

    function closeNav() {
      alert('esc pressed');
    }
    
    document.addEventListener('keyup', function(e) {
      if (e.keyCode == 27) {
        closeNav();
      }
    });

    But of course, there is no esc key in mobile, if you're trying to achieve that.