Calling a function on Bootstrap modal open
Asked Answered
M

7

249

I used to use jQuery UI's dialog, and it had the open option, where you can specify some Javascript code to execute once the dialog is opened. I would have used that option to select the text within the dialog using a function I have.

Now I want to do that using bootstrap's modal. Below is the HTMl code:

<div id="code" class="modal hide fade">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h3>Modal header</h3>
    </div>
    <div class="modal-body">
        <pre>
print 'Hello World'

And as for the button that opens the modal:

 <a href="#code" data-toggle="modal" class="btn code-dialog">Display code</a>

I tried to use an onclick listener of the button, but the alert message was displayed before the modal appeared:

$( ".code-dialog" ).click(function(){
    alert("I want this to appear after the modal has opened!");
});
Mores answered 4/7, 2013 at 4:3 Comment(3)
shown.bs.modal event occurs when HTML document contains at least <div class="modal fade"><div class="modal-dialog"></div></div> structure.Dispatch
dublicate https://mcmap.net/q/118798/-how-to-set-the-focus-for-a-particular-field-in-a-bootstrap-modal-once-it-appearsYeanling
Greet comment @Chemical Programmer, it should appear with the answerSaintebeuve
N
453

You can use the shown event/show event based on what you need:

$( "#code" ).on('shown', function(){
    alert("I want this to appear after the modal has opened!");
});

Demo: Plunker

Update for Bootstrap 3 and 4

For Bootstrap 3.0 and 4.0, you can still use the shown event but you would use it like this:

$('#code').on('shown.bs.modal', function (e) {
  // do something...
})

See the Bootstrap 3.0 docs here under "Events".

Nildanile answered 4/7, 2013 at 4:6 Comment(8)
Use $("#code").on("shown.bs.modal", function(e) {}) for bootstrap 3.0.Psychosomatic
make sure to take into account what Chemical Programmer said about needing the <div class="modal fade"><div class="modal-dialog"></div></div> structure at least for this code to be calledAyotte
The #code refers to the jQuery selector, one of the basic ingredients for jQuery: w3schools.com/jquery/jquery_selectors.aspBuild
I use $(document).on("shown.bs.modal", ... for overall listeningLotson
@Xatenev show is at the beginning of the event, shown is at the end. This is consistent across Bootstrap 3 and 4Contractile
The Bootstrap 3.0 works for me, but I get the alert first and the modal afterwards. Not that it matters in my case.Inconspicuous
At least the shown.bs.modal actually executes before the modal is shown. This is not a problem in my case, but may be good to know.Inconspicuous
@Lotson Thank you, that was exactly what I needed to do to overcome a set of restrictions that was tying my hands. You helped bring several days of suffering to an end just like that. Appreciated.Bricebriceno
M
118

will not work.. use $(window) instead

For Showing

$(window).on('shown.bs.modal', function() { 
    $('#code').modal('show');
    alert('shown');
});

For Hiding

$(window).on('hidden.bs.modal', function() { 
    $('#code').modal('hide');
    alert('hidden');
});
Mandell answered 28/4, 2014 at 15:18 Comment(6)
$( "#modal" ).on('shown', function(){ alert("I want this to appear after the modal has opened!");} Was not working for me but $(window) worked !! Thanks @MandellSalientian
I needed to bind to ANY modal that opened/closed, and not by a specific selector. This answer worked well for me in that case.Florina
This works before modal is fully loaded on GUI. I want to take data from my modal after modal is loaded - this method returns 'undefined' for everything because modal GUI is not yet existing, so fields and everything else is not queryable yet. (not visible)Thiamine
This worked for me, but I added a check within the handler to target one specific modal: if( $('#code').is( e.relatedTarget ) ) { ... } since I had multiple on the page.Fatherly
Thanks for the correct event name, but, there is no need to replace the element ID for $(window). Using bs4 with jquery 3.4.Shuster
with update to get specific modal in my bootstrap version was: if (shownEvent.target.id == 'uploadTemplateModal'){ }Slosh
U
35

you can use show instead of shown for making the function to load just before modal open, instead of after modal open.

$('#code').on('show.bs.modal', function (e) {
  // do something...
})
Uneventful answered 17/11, 2016 at 11:52 Comment(0)
T
11

Bootstrap modal exposes events. Listen for the the shown event like this

$('#my-modal').on('shown', function(){
  // code here
});
Traveller answered 4/7, 2013 at 4:7 Comment(1)
Replace shown with shown.bs.modal if using Bootstrap > 3Genro
S
4

This what worked with me to target specifec modal

$('#code').on('shown.bs.modal', function(){
  // code here
  alert('shown13');
});
Slosh answered 19/1, 2023 at 10:52 Comment(0)
G
0

if somebody still has a problem the only thing working perfectly for me by useing (loaded.bs.modal) :

 $('#editModal').on('loaded.bs.modal', function () {
       console.log('edit modal loaded');

       $('.datepicker').datepicker({
            dateFormat: 'yy-mm-dd',
            clearBtn: true,
            rtl: false,
            todayHighlight: true,
            toggleActive: true,
            changeYear: true,
            changeMonth: true
        });
});
Grebe answered 12/11, 2018 at 11:3 Comment(0)
L
0

With bootstrap 5

You can open the modal programmatically and simply call your method afterwards, so:

const modal = new bootstrap.Modal('#myModal')
modal.show()
alert('modal is showing')
Ligni answered 17/7, 2023 at 10:57 Comment(2)
Here you manually trigger the modal and fire off another manual alert. The original question wanted an event when the modal was shown programmatically. Bootstrap 5 would require binding with the shown event for the modal. myModalEl.addEventListener('shown.bs.modal', event => {}) getbootstrap.com/docs/5.2/components/modalJemine
@Jemine Thanks for the response. You're right, but at least for my case the effect was the same, so I'm leaving it, as it might help others as well.Ligni

© 2022 - 2024 — McMap. All rights reserved.