Search code examples
jquerytwitter-bootstrapmodal-dialogsetfocus

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


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();
    });
}

Solution

  • 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(); 
            });
        });
    }