I'm trying to do something (in this case some statistics) whenever a Bootrap modal is opened.
I know, I can ad an event listener like this to a modal:
$('#modal-content').on('shown.bs.modal', function() {
alert('do something');
});
But is there a way to have a listener for all modals on the page? Bonus question: even for those who are inserted by Javascript?
I have thought about something like this:
jQuery('.modal[role="dialog"]').on('show.bs.modal', function() {
alert('do something');
});
But I hope that there's a better way and something that will work for modals that are inserted by Javascript.
This ought to do the trick for you--it catches the event when it bubbles up to the document level, so that should catch them all:
$(document).on('shown.bs.modal', function() {
alert('do something');
});
See this bootply
HTH, -Ted
If you know the ids ahead of time, you could just list them out:
$('#modalOne, #modalTwo').on('shown.bs.modal', function() {
alert('do something');
});
Or better yet, if you are creating them programmatically as well as in html and are using a common prefix for the id, you can use the following:
$("div[id^='modal']").on('shown.bs.modal', function() {
alert('do something');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.