Bootstrap Modal Events fire multiple times, or rather always one more time then before. I wrap the modal events in a click function that returns the modal id for now.
How can I make sure the event always only fires once, and only when the click function invoked it?
jQuery
$('.img-modal').on('click', function () {
// returns #modal-Id
var modalIdClicked = $(this).attr('data-target')
console.log ('modal id clicked from .img-modal = '+ modalIdClicked);
console.log ('.img-modal clicked');
$(modalIdClicked).on('show.bs.modal', function(event) {
console.log ( 'show.bs.modal');
});
});
Default Bootstrap 3.3.2 Modal HTML
<div class="col-md-7">
<img class="img-modal img-responsive cursor-pointer" data-toggle="modal" data-target="#modal-1" src="www" alt="image">
</div>
<!-- Modal -->
<div class="modal fade top-space-0" id="modal-1" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content cursor-pointer" data-toggle="modal" data-target="#modal-1">
<div class="modal-header">
<button type="button" class="close" data-dismiss="#modal-1">CLOSE ×</button>
<h1 class="modal-title">Modal Title</h1>
</div>
<div class="modal-body">
<div class="img-center">
<img class="img-modal img-responsive" src="wwww" alt="image">
</div>
</div>
<div class="modal-footer">
<a href="#" class="btn btn-default" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
<!-- Modal end -->
I did have a look at jQuery click events firing multiple times and
Bootstrap 3 - Remotely loaded modal creates duplicate javascript events and it seems this can be achieved with the .off
method.
So using $(modalIdClicked).off().on('show.bs.modal', function(event) {
did the trick in this case.
Can someone please explain to me why this .off
method is needed in this case exactly? I am having trouble understanding how the click is passed around.
Does the click reach the Bootstrap JS one more time with every click? Why does it fire the events multiple times without the .off
method?
Thank you.
(I am trying to learn jQuery from a book, if any one out there really has a good book or even the one and only book to read about this, then please do shoot me a note, there is so many out there and all claim to be the best naturally.. thank you.)