<script language="javascript">
function toggle(id) {
alert('call');
if (document.getElementById(id).style.display == "none") {
alert('now visible');
document.getElementById(id).style.display = "";
} else {
alert('now invisible');
document.getElementById(id).style.display = "none";
}
}
</script>
</head>
<body onload="toggle('image1');alert('test_body');toggle('image2')">
<script language="javascript">
alert('test_pre_function');
toggle('image1');
alert('test_after_function');
toggle('image2');
</script>
Looks like a lot of code but it’s pretty simple so i think most of you won’t have troubles with it. toggle() should toggle the display status of divs containing images.
When the user enters the site the divs should hide, when everything is loaded the divs should show up. (onload)
Strangely enough, the function in the body (not in the body tag) only work half, i get and alert ‘test_pre_function’ and i get an alert ‘call’ (out of the function), but that’s it.
The code in the body tag runs just fine.
I find this weird because it’s supposed to do exactly the same twice and one time it runs, another time not, so i guess i must have made some stupid mistake.
Script is executed as soon as it is parsed. If
image1andimage2haven’t been parsed when the script is executed,document.getElementById("image1")will return null so.style.displaywill throw a “is null or not an object error”. This explains why the two alerts work – execution stops at the firstdocument.getElementById(id).style.display == "none"line.Move the script to after the image elements in the document and it should work.