Reputation: 5717
I have to draw something in bootstrap modal window if user click on button. My code is:
$('#button').on('click', function (evt) {
doSomeCrazyStuff();
$('#myModal').modal('show');
$('#myModal').on('shown.bs.modal', function (e) {
alert('Debug');
drawStuffInModal();
});
});
For first click everything works fine. But for second click i get two alerts, for third click - three alerts etc.
User can click button only if modal is hidden, so he need to close modal before next drawing.
I found out that a problem is a detecting of modal window state - if I don't use $('#myModal').on('shown.bs.modal', function (e) {})
but just waiting:
$('#button').on('click', function (evt) {
doSomeCrazyStuff();
$('#myModal').modal('show');
setTimeout(function () {
alert('Debug');
drawStuffInModal();
}, 500);
});
... I always get alert once. It works, but it's very ugly solution.
So my question is: why first code not working properly? I don't want wait n miliseconds because in some cases modal can need more time for loading and then user got errors.
Upvotes: 2
Views: 657
Reputation: 193261
Don't bind new event in another click event handler. Click on the #button
can happen many times, which means that it will bind many similar duplicated events. Just move shown.bs.modal
event subscription outside:
$('#myModal').on('shown.bs.modal', function (e) {
alert('Debug');
drawStuffInModal();
});
$('#button').on('click', function (evt) {
doSomeCrazyStuff();
$('#myModal').modal('show');
});
Upvotes: 1