Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple onload doesn't work in JSFIddle

http://jsfiddle.net/jzhang172/n5jb0159/

Simple document.body.onload event should trigger a javascript alert, but doesn't work but it works fine in my text editor -> browser. I switched the libraries around to jQuery to None (pure JS), still nothing, can someone explain to me what's going on and why it doesn't work in fiddle but works fine in my text editor?

This works:

  <body>
    Why
    <script>
  document.body.onload = function(){
      alert("LOADED!");
  }
  </script>
  </body>
like image 525
Snorlax Avatar asked Aug 11 '15 15:08

Snorlax


2 Answers

Your first problem:

Onload

You have configured JSFiddle to run your JS when the load event fires.

Consequently, when the load event fires, you bind another load event handler.

Your new load event handler is never called because the load event has already fired.

Change the menu option to one of the "No Wrap" approaches.


Your second problem:

The load event fires on the window object, not the body element.

You need to assign the property to the right place.

onload = function(){
  alert("LOADED!");
}

Such: https://jsfiddle.net/n5jb0159/5/

like image 160
Quentin Avatar answered Oct 24 '22 14:10

Quentin


You code is good, just change your JSFiddle option from this:

onLoad

to this:

No wrap - in <body>

Here is your updated JSFiddle

like image 36
Ahs N Avatar answered Oct 24 '22 13:10

Ahs N