0

I am trying to do this:

$(document).ready(function(){

    $('body').on('load', function(){
        alert('ok');
    });
    
});

But it not works.

Any help?

Italo Rodrigo
  • 1,555
  • 5
  • 17
  • 38

2 Answers2

1

First, you have to use $(window).load() instead of $('body').on('load'()). Then, you need to separate the onload() function and the ready() function:

  $(document).ready(function(){
  alert("fires when webpage is loaded");
  });

  $(window).on('load', function(){
      alert("fires once when window/body has been loaded");
  });

Have a look at this to understand the difference.

alexrogo
  • 522
  • 3
  • 17
1

Whay your code does not work?

When DOMContentLoaded event fires... That is the event that triggers the $(document).ready() callback. Obviouly, the body has already loaded too.

So if you wait for the whole DOM to be loaded to define an event handler about body loaded... It will never be executed because that event has fired before the event handler has been defined.


And after a close look: There is squarely no "load" event fired for the body... Whatever its content.

So as in pythan's answer, that should be $(window).on("load", function(){...})

See below:

console.log("before")
$("body").on("load", function () {  // That NEVER fires.
  console.log("Body loaded");
});
console.log("after")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <img src="https://via.placeholder.com/500" />
</body>

But anyway, you don't need both for sure.

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64