Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DOM objects not available when script is first run? 1

Status
Not open for further replies.

gs99

Programmer
Oct 7, 2001
40
0
0
Need to change objects depending on cookie values when script is first run.

Apparently the objects are not available, as seen in this test:

In html file:
<h3 id="hh1">Test color change in header</h3>
<input type="button" onclick="setColor()" value="Change color of header" />

In Javascript file:
function setColor()
{
document.getElementById("hh1").style.color="red";
}

When I click the button, it works OK - text changes to red.

But if I put this into Javascript file:
setColor();
to execute the function immediately, get "Object required" message.

Seems like a "document.read" is needed.
 
Thanks for your reply.

I'm using external script file, so can't use your suggestions, but further search confirms my observation that the DOM objects are not available until the page loads. Don't know where this simple fact is explained in DOM tutorials.

Global event handler - window.onload - must call a function.

In my simple test "window.onload = setColor;" works.
Note: setColor(); does not work.

More info:
 
Just include your script at the bottom of the page as clflava advised.
Code:
<html>
	<head>

		<script type="text/javascript">

		</script>
	</head>
	<body>
		<a href="[URL unfurl="true"]http://www.google.com">A[/URL] google link</a>
	<script type="text/javascript" src="yourjs.js"></script>
	</body>

</html>
 
try this little onload trick. I must say that I have run into problems of timing issues many times in the past. It will drive you crazy, I know. I have had scripts run perfectly for weeks make a change to some other place or the html and the script stops working and since the error occurs nothing may work. What point am I trying to make timing is every thing. Insert this text at the very bottom of your page just before the </html> tag
<script language="JavaScript" type=""text/javascript"">window.onload=function () {somefunction();}</script>
This will guarantee that all your js files are in the DOM and then this will also guarantee that the function executes after the pages loads. I use this in many places for many different purposes.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top