impossible to run jquery script when div is loaded, run jquery code before DOM load

I've looked for many solution but I can't find one... Can you help me ? I want to run a code when a div is loaded. I don't want to wait the end of the loading page.

So I'm using the $(sel).on('load', function(){ ... }); It's working when I'm putting $(window).on('load', function(){ ... }); but not when I specify the ID of the div $('#collapseTrack').on('load', function(){ ... });

Here is all my code : `

$('#collapseTrack').on('load', function(){

$('#nav-maps').on('click', function(event) {           
    $('#nav-maps').addClass('active').removeClass('inactive');
    $('#nav-trace').removeClass('active').addClass('inactive');           
});

$('#nav-trace').on('click', function(event) {           
    $('#nav-trace').addClass('active').removeClass('inactive');
    $('#nav-maps').removeClass('active').addClass('inactive');           
});



$('.collapse-nav').on('click', function(event) {

    $('#collapseTrack').toggleClass('DivClose').toggleClass('DivOpen');

    if ($('#collapseTrack').hasClass('DivClose')) {

        $('.collapse-button').html('<i class="fa fa-angle-down"></i>');
        $.cookie("toggle", 0, { expires : 10 });
    }

    else {

        $('.collapse-button').html('<i class="fa fa-angle-up"></i>');
        $.cookie("toggle", 1, { expires : 10 });
    }


});



if ($('#collapseTrack').hasClass('DivClose')) {

    $('.collapse-button').html('<i class="fa fa-angle-down"></i>');

}

else {

    $('.collapse-button').html('<i class="fa fa-angle-up"></i>');

}

});

`

Thanks !!!

Answers 1

  • There is no specific .load() event for a single div. So, the only time you can actually find the #collapseTrack div in your code is if you run some code after that div has been parsed and added to the DOM by the page loader or when it has been added to the page by some Javascript code.

    The simplest way to run code right after that div has been loaded is to place a <script> tag right after the <div> in your HTML.

    <div id="collapseTrack">Your HTML</div>
    <script type="text/javascript">
       $('#collapseTrack')....
    </script>
    

    Since the page is parsed sequentially, this ensures that all HTML that appears before this <script> tag in the page is already in the DOM and accessible before this <script> tag runs.


    If you're willing to wait until the page itself has been parsed to the end, you can do this:

    $(document).ready(function() {
        // waits for just the DOM to be finished parsing and inserted
        $('#collapseTrack')....
    });
    

    That will at least run earlier in the loading process than the window.load which waits for all page resources to finish loading (including images, style sheets, etc...):

    $(window).on('load', function() {
        // waits for all page resources to finish loading
        $('#collapseTrack')....
    });
    

Related Articles