Mohamed Khamis Mohamed Khamis - 1 year ago 138
Javascript Question

Calling a function on bootstrap modal open

I used to use JQuery UI's dialog, and it had the

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 class="modal-body">
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!");

Answer Source

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.0

For Bootstrap 3.0 you can still use the shown event but you would use it like this...

$('#code').on('', function (e) {
  // do something...

See the bootstrap 3.0 docs here under "Events".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download