CSS/HTML Modal- Using the Escape key/Click outside to close

混江龙づ霸主 提交于 2019-11-30 14:32:54

For this you will need a little javascript. Check the code with some comments.

function modalClose() {
    if (location.hash == '#openModal') {
        location.hash = '';
    }
}

// Handle ESC key (key code 27)
document.addEventListener('keyup', function(e) {
    if (e.keyCode == 27) {
        modalClose();
    }
});

var modal = document.querySelector('#openModal');

// Handle click on the modal container
modal.addEventListener('click', modalClose, false);

// Prevent event bubbling if click occurred within modal content body
modal.children[0].addEventListener('click', function(e) {
    e.stopPropagation();
}, false);

Demo: http://jsfiddle.net/GG9Sa/264/

Note, that closing modal is technically possible with CSS/HTML only, however for handling Escape key press you will need Javascript.

Suraj Rotkar

just write these lines in your head tag

$(document).on('keyup',function(evt) {
  if (evt.keyCode == 27) {
    location.href="#close";
  }   
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!