3

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();
    });
}
Community
  • 1
  • 1
Gauthier
  • 1,116
  • 2
  • 16
  • 39

2 Answers2

3

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(); 
        });
    });
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • It doesn't work. I don't understand. I removed the autofocus and used your function and the focus doesn't work. But i can see the modal with means that the .modal("show") is executed – Gauthier Dec 02 '14 at 10:01
  • No errors in the console. I add something in my post, have a look – Gauthier Dec 02 '14 at 10:06
  • Does the modal show with an animation, such as `fadeIn()`? It's possible the element is not available in the DOM until the animation completes. – Rory McCrossan Dec 02 '14 at 10:10
  • Oh smart ! this is the modal i use : http://bootstrap2modaldemo.scripting.com/# How should I do if this is the problem ? Do you have any idea ? – Gauthier Dec 02 '14 at 10:17
  • In that case you need to use the `shown` callback. I've updated my answer for you. – Rory McCrossan Dec 02 '14 at 10:19
  • Nice, it's working very well. Thanx a lot, you taught me a lot. I don't use callback as I should. – Gauthier Dec 02 '14 at 10:26
1

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();
});
Cerlin
  • 6,622
  • 1
  • 20
  • 28