Robin Carlo Catacutan
Robin Carlo Catacutan

Reputation: 13679

body onload and window.onload at the same time

Can I use body onload and window.onload at the same time? I've tried it using this code

<body onload = "alertFirst()">
</body>
<script>
    window.onload = alertSec;
</script>

But it didn't work. I just need someone to confirm it to me. Many thanks

Upvotes: 0

Views: 5499

Answers (4)

J. K.
J. K.

Reputation: 8368

No, document.body.onload is actually mapped to window.onload. You can check yourself—when you have <body onload="a()"> and to console.log(window.onload), a() is printed out into the console.

What you can do is to have one onload event handler that calls two other functions.

window.onload = function () {
  a();
  b();
};

or two event listeners

window.addEventListener('load', a, false);
window.addEventListener('load', b, false);

Upvotes: 1

Umbrella
Umbrella

Reputation: 4788

The answer to your question is "no". However there are ways around it.

Adding both calls to one onload function is ideal, but if you /have/ to add an onload handler after one is already added, and you are not using a framework which facilitates this, you can get by like this:

<html>
    <head>
        <script type="text/javascript">
            function alertFirst(){
                alert('First');
            }
            function alertSec(){
                alert('Second');
            }
        </script>
    </head>
    <body onload="alertFirst();">
        content
    </body>
    <script>
        var func = document.body.onload;
        window.onload=function(){
            func();
            alertSec();
        }
    </script>
</html>

Upvotes: 2

Django Anonymous
Django Anonymous

Reputation: 3025

If one or more of the scripts you want to use has the event handler in the BODY HTML tag, you can still move it to into javascript code. See the example below:

Script #1:

<script language="javascript">

function start(){
...code for script #1...
}

</script>

<body onload="start()">

Script #2:

<script language="javascript">

function init(){
...code for script #2...
}

window.onload=init;

</script>

Result:

<script language="javascript">

function start(){
...code for script #1...
}

function init(){
...code for script #2...
}

window.onload=function(){
start();
init();
}

</script>

<body>

I think it may can help you.

Upvotes: 0

mplungjan
mplungjan

Reputation: 177851

You can (by adding event handler(s)) but you should NOT have both

Instead add the call to the window.onload:

<html>
<head>
<script>
  window.onload = function() {
    alertFirst();
    alertSec();
  }
</script>
</head>

<body>
</body>

Upvotes: 1

Related Questions