Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 913
Andrey_ Avatar asked May 18 '26 06:05

Andrey_


1 Answers

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. ;)

like image 114
ThiefMaster Avatar answered May 19 '26 20:05

ThiefMaster