'How do you enable the escape key close functionality in a Twitter Bootstrap modal?
I followed the instructions for the Twitter Bootstrap modal on their main documentation page
and used the data-keyboard="true" syntax mentioned but the escape key does not close the modal window.
Is there something else I'm missing?
Code:
<a href="#my-modal" data-keyboard="true" data-toggle="modal">Open Modal</a>
<div class='modal fade hide' id='my-modal'>
<div class='modal-body'>
<div>Test</div>
</div>
</div>
Solution 1:[1]
also if you're invoking via javascript , use this:
$('#myModal').modal({keyboard: true})
Solution 2:[2]
add tabindex="-1" attribute to modal div
<div id="myModal" class="modal fade" role="dialog" tabindex="-1">
</div>
Solution 3:[3]
In angular I am using like this:
var modalInstance = $modal.open({
keyboard: false,
backdrop: 'static',
templateUrl: 'app/dashboard/view/currentlyIneligibleView.html',
controller: 'currentlyIneligibleCtrl',
resolve: {
data: function () { return param; }
}
});
- backdrop: 'static' => Stop to close on clicking outside
- keyboard: false => Stop to close by using escape buttton
Solution 4:[4]
let modals = []
$(document).keyup(function(e) {
if((e.key=='Escape' || e.key=='Esc' || e.keyCode==27) && modals.length) {
$(".modal[modal='" + modals.pop() + "']").modal('hide')
}
})
$(".modal").on("shown.bs.modal", e => {
const id = modals.length
modals.push(id)
$(e.target).attr("modal", id)
})
Solution 5:[5]
Bootstrap 3
In HTML, just set data-backdrop to static and data-keyboard to false
Example :
<button type="button" data-toggle="modal" data-target="#myModal" data-backdrop="static" data-keyboard="false">Launch modal</button>
or
$('#myModal').modal({
backdrop: 'static',
keyboard: false
})
Live Test :
https://jsfiddle.net/sztx8qtz/
Know More : http://budiirawan.com/prevent-bootstrap-modal-closing/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dennisbot |
| Solution 2 | FelixSFD |
| Solution 3 | Ali Adravi |
| Solution 4 | yassine |
| Solution 5 | Rashedul Islam Sagor |
