Why is my function not working when loading a document as expected?

This code should set the height of the elements; however, the style is not added. Am I missing something?

function setGround() { 
    document.getElementById('content').style.height = '40px';
} 

document.onload = setGround; 

HTML is pretty simple:

<!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Template</title>
    <link rel="stylesheet" type="text/css" href="css/default.css"/>
    <link rel="stylesheet" type="text/css" href="css/orange.css"/>
    <script type="text/javascript" src="javascript/detect-css.js"></script>
</head>

<body>
    <header>
        <div id="logo"></div>
    </header>
    <section id="sidebar"><p>sf </p>
    </section>

    <section id="content"><p>sf </p>
    </section>

</body>
</html>

Thank you for your help!

+5
source share
4 answers

Do not use document.onloadinstead window.onload.

See http://jsfiddle.net/mowglisanu/r6NzE/

+4
source

you can use this:

function setGround() { 
    document.getElementById('content').style.height = '40px';
} 
document.onload = setGround;

but if you want to see the changes, you must create a border in the section tag using this:

<section id="content" style='border:1px solid fuchsia;' >
<p>sf </p>
</section>     
+2
source

You have to use

window.onLoad = setGround; 

instead

document.onload = setGround;
+1
source

Where did you place the javascript code? Is this in detector-css.js?

It works:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Template</title>
<link rel="stylesheet" type="text/css" href="css/default.css"/>
<link rel="stylesheet" type="text/css" href="css/orange.css"/>
<script language="javascript">
function resize(){
document.getElementById("content").style.height='100px';
}
</script>
</head>

<body onload="resize()">
<header><div id="logo"></div></header>
<section id="sidebar"><p>sf </p>
</section>

<section id="content" style="background-color:#CCC; display:block;"><p>sf </p>
</section>

</body>
</html>
0
source

All Articles