How can i kill an already opened Bootstrap modal? jsFiddle example:
<script>
$(function(){
$('#myModal').on('show', function() {
if(true) { /* Kill (close) this modal on some condition */}
});
});
</script>
I’ve tried:
if(true) { $('#myModal').modal('hide'); } // Not working
if(true) { $('#myModal').modal('toggle'); } // Too much recursion!!! :P
if(true) { return; } // Nope
First, as @ChristianEngel correctly pointed out, the JSFiddle you provided in your question is listening to the
showevent on a non-element (#modal-delete), whereas it should be attached to the actual modal (#myModal) [which you did correctly in your code].Second, despite that correct observation, I can still attest that I am seeing the behavior that you are complaining about, and here’s why: the show event is triggered before the actual modal has been shown, and hence your call to
hide()is made before the rest of theshow()code. One way to fix it would be to listen to theshownevent instead. That is not the way to do it!!The correct way to do what you are attempting is to simply call
preventDefault()on the event.JSFiddle
This will save a whole bunch of unnecessary code being executed.
By the way, I’ll just add that I think this scenario illustrates quite well the reason for having both a
showand ashownevent. While not the only reason for theshowevent, having it trigger before the action occurs allows for the developer to cancel it when required.