Oriam
Oriam

Reputation: 641

How to trigger the ajax onload/success event for bootstrap3 dialog

I have a bootstrap dialog taking data from remote location, it work fine. I want to execute some js code after the content had been loaded (by ajax). I try

.on('shown.bs.modal', function...  

but this is triggered immediately after modal is shown, and before content are loaded. Thank in advance

Update:

this is the link to display the modal

<a data-toggle="modal" data-target="#modalX" class="" href="path/to/data.html">
    some text
</a>

this is the empty modal (before the ajax call to load content from "path/to/data.html"

<div class="modal fade" id="modalX" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">X</button>
      <div class="modal-body">
          Cargando ... / Loading ...
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

js event code...

$('#modalX').on('shown.bs.modal', function () {
    //not good to use in on ajax load :(
})

Upvotes: 1

Views: 4749

Answers (1)

dcodesmith
dcodesmith

Reputation: 9614

Ok, there is this issue with the bootstrap guys refusing to provide an onload or loaded event upon data being loaded with the remote option.

So the way around this is as follows:

Create a custom/basic anchor tag to trigger the Modal open

<a class="open-modal">
    Open Modal
</a>

Your Modal container

<div class="modal fade" id="modalX" tabindex="" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    ......
    ......
</div>

JS

$(document).ready(function(){
    $('a').on('click', '.open-modal', function(e){
        e.preventDefault();
        $('#modalX').modal({
            show: true,
            ....
        })
        .load('path/to/data.html', function(e){
            alert(e); // where e is the content
            // do what it is you need to do in here
        });
    });
});

Update

The Bootstrap guys seem to have finally agreed to add the loaded event to the modal component in version 3.1.0

Now you can do ..

$('#modalX').on('loaded.bs.modal', function (e) {
  // do something...
});

Upvotes: 2

Related Questions