The popular solution to put a setTimeout
could work in some case, but is a terrible solution. I was myself using it amongst wraping it in $(document).ready()
off course (but it never helped), but I was never able to have a reliable solution. Some browser/system take more time than other, and sometime 1000ms
was not enough. And I was tired searching why the $(document).ready()
wasn't helping, so :
I took a different approach.
I make the subscription to modal events when I need to use the modal for the first time.
<a href="javascript:void(0)" onclick="ShowModal()">Open my modal</a>
and on the JS side :
function ShowModal() {
InitModalEventsOnce();
$('#MyModal').modal('show');
}
var InitModalEventsIsDone = false; // Flag to keep track of the subscribtion
function InitModalEventsOnce() {
if (!InitModalEventsIsDone) {
InitModalEventsIsDone = true;
$('#MyModal').on('shown.bs.modal', function () {
// something
})
$('#MyModal').on('hidden.bs.modal', function (e) {
// something
});
}
}
And that's it! The only reliable solution I found.