Forum Moderators: open

Message Too Old, No Replies

Script doesn't work when moved into head

         

Jeremy_H

12:29 am on Jun 9, 2006 (gmt 0)

10+ Year Member



Hello,

The following script works fine if the script follows the DIV tag, but doesn't seem to work if the script is in the head, where I would really like to put it.

Am I doing something wrong, or is there something I can do that would allow me to move the script?

Also, does anybody see any flaws with the script? Would the way it is being called work in both IE, FF, and other browsers with JavaScript turned on?

Thanks.

<html>
<head>
<script type="text/javascript">
function count(){
....
}
document.getElementById("a").onclick=count;
</script>
</head>

<body>
<div id="a"><a href="...">Text</a></div>
</body>
</html>

adni18

12:32 am on Jun 9, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yep. getElementById("a") doesn't work, because "a" hasn't been created yet. You need to call the function after "a" has been created in the HTML code. :)

Jeremy_H

1:07 am on Jun 9, 2006 (gmt 0)

10+ Year Member



Thanks for the reply,

Would it help if I wrap the getElementById line in another script that doesn't load until later, like:

<script type="text/javascript">
function count(){...}

document.onclick{
document.getElementById("a").onclick=count;
}
</script>

adni18

1:18 am on Jun 9, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



try:

<script type="text/javascript">
<!--
function count(){...}

document.onload = function() {
document.getElementById("a").onclick=count;
}
//-->
</script>

it might be document.body.onload, actually. or window.onload. I'm not sure, and I'm too lazy to look it up :P.

DrDoc

2:43 am on Jun 14, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



... and, while you're at it, get those HTML comments outta there, as they don't belong in JavaScript. ;)

adni18

5:02 am on Jun 17, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hmm? Oh, the <!-- and //-->? I always thought those were meant to hide the code from javascript-deficient browsers?