Escape key does not close the modal dialogue box

I’ve customized the codrops slide & push menu (http://tympanus.net/codrops/2013/04/17/slide-and-push-menus/) to create an overlay on a webpage. Although it functions as intended, I’m struggling to implement a way to close it by pressing the escape key. Any assistance would be greatly appreciated. Thank you.

jsfiddle (with non-working code): https://jsfiddle.net/kreemers/0f5kv3px/

jsfiddle (working modal without ESC functionality): https://jsfiddle.net/kreemers/0f5kv3px/3/

HTML:

<nav class="modal modal-vertical modal-right" id="modal">
  <h1>CONTENT</h1>
</nav>

<h1 id="showRight">OPEN</h1>
<h1 id="hideRight">CLOSE</h1>

CSS:

/* GENERAL */

.modal {
  background: yellow;
  position: fixed;
  margin-left: 20px;
}

h1 {
  margin-left: 20px;
}


/* Orientation-dependent styles for the content of the menu */

.modal-vertical {
  width: 60%;
  height: 100%;
  top: 0;
  z-index: 1000;
}

.modal-right {
  right: -60%;
}

.modal-open {
  right: 0px;
}


/* Push classes applied to the body */

.modal-push {
  overflow-x: hidden;
  position: relative;
  left: 0;
}


/* TRANSITION */

.modal,
.modal-push {
  -webkit-transition: all 0.6s ease;
  -moz-transition: all 0.6s ease;
  transition: all 0.6s ease;
}

JAVASCRIPT:

/* MODAL*/
var
  menuRight = document.getElementById('modal'),
  body = document.body;



showRight.onclick = function() {
  classie.removeClass(hideRight, 'active');
  classie.addClass(this, 'active');
  classie.addClass(menuRight, 'modal-open');
  disableOther('showRight');
};

hideRight.onclick = function() {
  classie.removeClass(showRight, 'active');
  classie.addClass(this, 'active');
  classie.removeClass(menuRight, 'modal-open');
  disableOther('hideRight');
};


function disableOther(button) {
  if (button !== 'showRight') {
    classie.toggle(showRight, 'disabled');
  }
};



/* CLOSING MODAL WITH ESC THAT ISN’T WORKING*/
$(document).click(function() {
  if (isOpen) {
    classie.removeClass(menuRight, 'modal-open');
    classie.addClass(this, 'active');
  }
});

$(document).keyup(function(e) {
  // ESCAPE key pressed
  if (e.keyCode == 27) {
    if (isOpen) {
      classie.addClass(this, 'active');
      disableOther('hideRight');
    }
  }
});


/*
 * classie - class helper functions
 * from bonzo https://github.com/ded/bonzo
 */

(function(window) {

  'use strict';

  // class helper functions from bonzo https://github.com/ded/bonzo

  function classReg(className) {
    return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
  }

  // classList support for class management
  // although, to be fair, the api sucks because it won't accept multiple classes at once
  var hasClass, addClass, removeClass;

  if ('classList' in document.documentElement) {
    hasClass = function(elem, c) {
      return elem.classList.contains(c);
    };
    addClass = function(elem, c) {
      elem.classList.add(c);
    };
    removeClass = function(elem, c) {
      elem.classList.remove(c);
    };
  } else {
    hasClass = function(elem, c) {
      return classReg(c).test(elem.className);
    };
    addClass = function(elem, c) {
      if (!hasClass(elem, c)) {
        elem.className = elem.className + ' ' + c;
      }
    };
    removeClass = function(elem, c) {
      elem.className = elem.className.replace(classReg(c), ' ');
    };
  }

  function toggleClass(elem, c) {
    var fn = hasClass(elem, c) ? removeClass : addClass;
    fn(elem, c);
  }

  window.classie = {
    // full names
    hasClass: hasClass,
    addClass: addClass,
    removeClass: removeClass,
    toggleClass: toggleClass,
    // short names
    has: hasClass,
    add: addClass,
    remove: removeClass,
    toggle: toggleClass
  };

})(window);

Answer №1

To implement the "onkeyup" event, you can use the following JavaScript code:

var
  menuLeft = document.getElementById('sidebar'),
  body = document.body;



openSidebar.onclick = function() {
  classie.removeClass(closeSidebar, 'hidden');
  classie.addClass(this, 'active');
  classie.addClass(menuLeft, 'show-sidebar');
  disableOther('openSidebar');
};

document.onkeyup = function(event){
  var key = event.keyCode;
  if(key == 27) {
    closeSidebar.click();
  }
}

closeSidebar.onclick = function() {
  classie.removeClass(openSidebar, 'active');
  classie.addClass(this, 'hidden');
  classie.removeClass(menuLeft, 'show-sidebar');
  disableOther('closeSidebar');
};


function disableOther(button) {
  if (button !== 'openSidebar') {
    classie.toggle(openSidebar, 'disabled');
  }
};

Check out the JSFiddle demo here: https://jsfiddle.net/0f5kv3px/8/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sorting rows by words and numbers in JavaScript explained

Hello, I'm a beginner and I need help sorting the table rows in the following table. I also want to attach an onclick listener to the header after it is displayed. ID Name Inventory Volume 1 Rachel Data is not enough 2 Ross 100 3 Monica 1 ...

Universal Module Identifier

I'm trying to figure out how to add a namespace declaration to my JavaScript bundle. My typescript class is located in myclass.ts export class MyClass{ ... } I am using this class in other files as well export {MyClass} from "myclass" ... let a: M ...

What is the difference in speed between drawing on a transparent canvas and determining if a point is transparent compared to determining if a point is within a complex polygon?

I'm curious if anyone has done research on adding event support to a game engine. Specifically, I am working on incorporating pixel-perfect hover over 2D object event support into my own game engine. I am exploring different ways of achieving this eff ...

Beautify JSON data display

My JSON object is displaying differently when I alert it: https://i.stack.imgur.com/lwNIJ.png I would like it to show like this instead: https://i.stack.imgur.com/cVakX.png function getEmployeeNameById(id){ return staffArray.find(item => item. ...

Troubleshooting a Custom Menu Control in HTML

Would you mind taking a look at the menu I have set up in this fiddle: http://jsfiddle.net/Gk_999/mtfhptwo/3 (function ($) { $.fn.menumaker = function (options) { var cssmenu = $(this), settings = $.extend({ title: "Menu", ...

What is the best way to create a design with an image on the left and text on the right side?

I am trying to create a layout that features an image on the left and text on the right in a specific structure: Item 0: value 0 Item 1: value 1 Item 2: value 2 However, the text is appearing all in one row like this: Item 0: value 0 Item 1: value 1 Ite ...

Establish individual states for every dynamically created component using the same handler function

I have a component in React built with Material UI, where the child component (Paper) is dynamically generated depending on the number of items in an array. The challenge I'm facing is changing the elevation property of the Paper component when it&ap ...

Shifting annotations on a Bar Graph featuring Negative Values on Google's Chart Maker

Incorporating google charts into my MVC project. Looking to create a bar chart that accommodates negative values. Desire annotations on the same side as the end of the bar for negative values (similar to positive values shown in the green box below). ht ...

Adjust parameters using JavaScript and three.js in real-time

I am not well-versed in JavaScript and I am facing an issue. I need to dynamically change the parameter passed to a function written in JavaScript, but the code is structured in a way that is unfamiliar to me. Therefore, I am seeking assistance. On my web ...

Encountering an error while attempting to launch an AngularJS application on Node.js? Let's

Currently, I am in the process of learning Angular. Whenever I attempt to run my code, an error message pops up: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7a737a7c6b6d70715f2b312f3115">[email protected]< ...

Encountering the error message "Angular 'undefined is not a function' when trying to define a component

My Ionic code was originally working fine, allowing the user to input a list. I decided to refactor it into a component for re-usability but encountered an error undefined is not a function on line 4 of the Javascript file. How can this issue be resolved? ...

Identifying modifications to the content of a text area

Is there a way to determine if the value in my textareaId has changed due to JavaScript? For example: $("#buttonID").on("click, function(){ $("#textareaID").val("lorem ipsum"); }); $("#textareaID").change(function(){ //not working }); $ ...

Is there a way to deactivate the onClick event when the dropdown placeholder is chosen?

I have experimented with different methods to prevent the onClick event when selecting either placeholder, but I have not been successful. Here is my current code: <div class="choosesign"> <div class="zodiacs"> < ...

What methods can I employ JSON to create a dynamic Sidebar within Nextjs?

[ { "type": "root", "children": [ { "type": "file", "route": "Open-EdTech/AWS-Associate-Notes/EC2.md", "title": "EC2", ...

Ways to implement material-ui button design on an HTML-native button

I am using pure-react-carousel which provides me an unstyled HTML button (ButtonBack). I would like to customize its style using material-ui. Trying to nest buttons within buttons is considered not allowed. An approach that works is manually assigning th ...

Webpage Text Animation

This is the visual representation of my webpage: https://i.stack.imgur.com/tYq34.png I am seeking to implement a uniform animation effect for the text "Carlos Qiano" and "Lorem Ipsum", similar to the link below: https://i.stack.imgur.com/XVnBS.jpg Note: ...

Button for toggling the mobile navbar in Bootstrap

Is there a way to adjust the position of the navbar-toggle button http://prntscr.com/5sldgb within the navbar after changing its height? Here is the HTML code: <div class="navbar navbar-default"> <div class="container"> ...

Retrieve information following an Ajax call inside a pre-designed template

Upon rendering a page with data put together by EJS, the goal is to refresh a section (thirdRow) of the page whenever the user submits new data. The refreshed section should display both the newly submitted data and the existing data. Although I have obtai ...

What is the best way to retrieve the column that comes after a specific column?

I have a specific column and I want to extract the subsequent column in the dataset. nhood,column,variablecolumn Treasure Island,3,5 McLaren Park,1,2 Tenderloin,28,112 Lakeshore,14,8 Chinatown,15,103 Although I know the name of the second column, the na ...

How can I use PHP and JavaScript to iterate through a <select> / <option> list and gather the values?

I am working on a project where I have a group of options within a selection dropdown and my goal is to utilize JavaScript to deselect all chosen values, gather them into a string, and then send it over to my PHP script. ...