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.
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.
Share Improve this question asked Feb 19, 2015 at 16:15 wawawawa 5,0845 gold badges35 silver badges59 bronze badges2 Answers
Reset to default 12This 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 mon prefix for the id, you can use the following:
$("div[id^='modal']").on('shown.bs.modal', function() {
alert('do something');
});