How to wait for the full load of a bootstrap modal-dialog loaded with jquery .load() function

7.5k views Asked by At

I have severals bootstraps modals in my website, and I load them like this :

function modal_density(){
    $("#modal-content").load("pages/modals/density_control.php");
    $('#all_modal').modal('show');
}

Then I close them like this :

function close_modal(){
    $("#modal-content").empty();
    $('#all_modal').modal('hide');
}

I want to put focus in an input of my modal, but I think that the modal is not fully loaded when I try to do that :

function modal_density(){
    $("#modal-content").load("pages/modals/density_control.php");
    $('#all_modal').modal('show');
    $("#element").focus();//<----Added part
}

How to wait for the full load of my elements ?


[EDIT]: I tryed this and it doesn't work :

function modal_controle_densite_valid(){
    $("#modal-content").load("pages/modals/controle_densite_validation.php", function() {
        $('#all_modal').modal('show');
        $("#codebarre").focus();
    });
}

But the following code is working after 2 sec :

function modal_controle_densite_valid(){
    $("#modal-content").load("pages/modals/controle_densite_validation.php", function() {
        $('#all_modal').modal('show');
        setTimeout(function() {$("#codebarre").focus()}, 2000);
        //$("#codebarre").focus();
    });
}
2

There are 2 answers

6
Rory McCrossan On BEST ANSWER

The load() method has a second parameter which allows you to provide a function which should be executed whent he AJAX request completes. Try this:

function modal_density(){
    $("#modal-content").load("pages/modals/density_control.php", function() {
        $('#all_modal').modal('show').on('shown', function() {
            $("#codebarre").focus(); 
        });
    });
}
0
Cerlin On

jquery load takes a callback which will get executed after the loading is done

$("#modal-content").load("pages/modals/density_control.php",function(){
    $("#element").focus();
});