Snorlax
Snorlax

Reputation: 4735

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>

Upvotes: 7

Views: 6368

Answers (4)

eQ19
eQ19

Reputation: 10691

There also one notice against the behavior in jQuery for onload event behavior in JSFIddle.

Testing code in HTML DOM addEventListener() Method is as below:

window.addEventListener('load', initialProcess, false);

LOAD TYPE: onLoad https://jsfiddle.net/chetabahana/a9dxv3fb/5/

When Load type set to onLoad, the event doesn't fires an excecution

onLoad option of jQuery 3.3.1 in JsFiddle

LOAD TYPE: onDomready https://jsfiddle.net/chetabahana/a9dxv3fb/6/

When it was set onDomready, the event fires and works fine

enter image description here

Upvotes: 0

IE5Master
IE5Master

Reputation: 413

I was able to get it working http://jsfiddle.net/n5jb0159/8/

Just put the script inside the body.

<body>
    <script>document.body.onload = function(){alert("sdffds")}</script>
</body>

Upvotes: 0

Ahs N
Ahs N

Reputation: 8366

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

onLoad

to this:

No wrap - in <body>

Here is your updated JSFiddle

Upvotes: 3

Quentin
Quentin

Reputation: 943142

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/

Upvotes: 8

Related Questions