Dimitrios
Dimitrios

Reputation: 3

$(window).load(function() fails to execute after completely loaded document

I have failed to find the answer in the following:

I have an html document that loads a couple of other htmls. This is done perfectly.

However, in on one of the included htmls, the "navmenu.html", I would like, after everything is comlepetly loaded, to execute a script found in load() to modify "menu1" element's class, which is in the included "navmenu.html".

After the ready() function, the load() function is executed before the "navmenu.html" is really & completely included in the document, since I get the error message that the element "menu1" is not found.

If I pause the action by an alert() at the beginning of load() - then the menu1 element is found - since this delay caused by the alert() gives time to the ready() function to complete.

So, is there a way to solve this?

Thank you in advance.

<body>
    <div id="navmenu"></div>
    <div id="carousel"></div>
</body>

<script language="javascript" type="text/javascript">
    jQuery( document ).ready(function( $ ) {
        $('#navmenu').load('navmenu.html');
        $('#carousel').load('carousel.html');
    });

    $(window).load(function() {
      var element = document.getElementById("menu1");
      element.classList.add("active");
    });
</script>

Upvotes: 0

Views: 334

Answers (2)

Dimitrios
Dimitrios

Reputation: 3

Thank you so much Radu Toader for the reply. It worked !!!

(I am not sure if this is the right way to answer, since it's my first question to the group.)

I also tried the following, since the element was in "navmenu.html" and had a separate line for the carousel.

$('#navmenu').load('navmenu.html',[],function(){
    var element = document.getElementById("menu1");
    element.classList.add("active");
});
$('#carousel').load('carousel.html');

I also tried your answer where load.carousel was called by the load.navmenu and it also worked.

Do you suggest that I should use your "more complex" solution instead of the separated line for the carousel?

Thanks again.

Dimitrios

Upvotes: 0

Radu Toader
Radu Toader

Reputation: 1561

jQuery.load() has the following signature (url,data,callbackFunction).

You could try the followind :

jQuery( document ).ready(function( $ ) {
    $('#navmenu').load('navmenu.html',[],function(){
         $('#carousel').load('carousel.html',[],function(){
             var element = document.getElementById("menu1");
             element.classList.add("active");
         });
    });
});

Upvotes: 5

Related Questions