Skip to content

Close a Modal using the ESC Key? / Cerrar Modal usando ESC

JavaScriptJQuery

 

 

 

$(document).ready(function(){

    $('.modal').modal({show: false, keyboard: false}); // disable keyboard because it conflicts below

    $('.modal').on('show.bs.modal', function (event) {
       //add modal id to array
       modals.push(event.target.id);
    });


    document.onkeydown = function(evt) {
        evt = evt || window.event;
        var isEscape = false;
        if ("key" in evt) {
            isEscape = (evt.key === "Escape" || evt.key === "Esc");
        } else {
            isEscape = (evt.keyCode === 27);
        }
        if (isEscape) {

            if(modals.length>0){
                //get last modal id by using pop(). 
                //This function also removes last item in array.
                var id = modals.pop();
                if($('#'+id).is(':visible')){ // if modal is not closed by click or close button
                    $('#'+id).modal('toggle');
                }
            }else{
                alert("Could not find any modals!");
            }
        }
    };

});

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

No comments

Add Comment

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
Standard emoticons like :-) and ;-) are converted to images.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications.
To leave a comment you must approve it via e-mail, which will be sent to your address after submission.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Form options

Submitted comments will be subject to moderation before being displayed.