Andrey_
Andrey_

Reputation: 155

JavaScript onload and DOM

I have this example document:

<html>
    <body>
        <script type="text/javascript">
            document.body.onload = myFunc();

            function myFunc() {
                element = document.getElementById('myDiv');
                element.innerHTML = 'Hello!';
            }
        </script>
        <div id="myDiv"></div>
    </body>
</html>

Why 'element' is null if myFunc is a callback of document.body.onload?

If, instead, the script is inserted after the div, it works:

<html>
    <body>
        <div id="myDiv"></div>
        <script type="text/javascript">
            document.body.onload = myFunc();

            function myFunc() {
                element = document.getElementById('myDiv');
                element.innerHTML = 'Hello!';
            }
        </script>
    </body>
</html>

My question is: if I use the onload event within the handler function, should I have the entire DOM, or not? Why should I not?

Upvotes: 3

Views: 4603

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318508

The problem is that you are calling the function immediately (and assign its return value).

Assign the function instead and it will work:

document.body.onload = myFunc;

You should also use var element in your function to avoid creating a global variable.


Or if you want to confuse people:

document.body.onload = myFunc();
function myFunc() {
    return function() {
        var element = document.getElementById('myDiv');
        element.innerHTML = 'Hello!';
    };
}

But let's not do that. It makes no sense here. ;)

Upvotes: 2

VisioN
VisioN

Reputation: 145398

Use this instead

document.body.onload = myFunc;

Or

document.body.onload = function() {
    myFunc();
};

Upvotes: 0

Related Questions