jQuery toggle by ESC and clicking

59 views Asked by At

I have this simple script

$(".showHide").click(function (e) {
    e.stopPropagation();
    jQuery(this).children('.showHide').toggle();
});

I don't know how to 1) Hide .modal if is ESC presed 2) Hide .modal if user click outside of .modal-inside

https://jsfiddle.net/zkx9gt2u/1/

1

There are 1 answers

1
Rash On BEST ANSWER

This should do the trick.

$(".showHide").click(function (e) {
    e.stopPropagation();
    $(".showHide").children('.showHide').toggle();
});

$(".modal-inside").click(function (e) {
    e.stopPropagation();
});

$(document).bind('keydown', function(e) { 
        if (e.which == 27) {
            $(".showHide").children('.showHide').hide();
        }
    });

Edit

I recently came across bootstrap modal which got added in v3. It does exactly what you want. A good starting point would be official site and here.

E.g. if you wish to close your modal using esc key, all you have to do is this:

var options = {
    "backdrop" : "static"
}

$('#id-of-modal').modal(options);