Reputation: 32143
I'm doing something wrong but WHAT! I've looked over it a hundred times. For some reason, it isn't retrieving the object from the document. Here is my index and Javascript source:
var blinkOn =false;
var blinkObj=document.getElementById("blink");
function blinkCursor() {
if (blinkOn)
{
blinkObj.style.display="none";
} else {
blinkObj.style.display="inline";
}
blinkOn=!blinkOn;
setTimeout("blinkCursor()",500);
}
blinkCursor();
INDEX:
<html>
<head>
<title>
CMD.exe
</title>
<link rel="stylesheet" type="text/css" href="cmd.css" />
<script language="JavaScript" SRC="cmd.js"></script>
</head>
<body>
<span id="content">></span><span style="display:none;" id="blink" >|</span>
</body>
</html>
Any help would be so much help! (well.. wait... duh :p )
Upvotes: 0
Views: 123
Reputation: 50592
Instead of getting the element in the global scope, grab a reference within the function. This prevents the function from failing if it is called when the element doesn't exist.
You could also call this from body::onLoad
/onDomReady
instead, depending on framework/preference.
function blinkCursor() {
var blinkObj=document.getElementById("blink");
if (blinkObj) {
blinkObj.style.display=(blinkObj.style.display == "none") ? 'inline' : 'none';
}
}
function stopBlink() {
clearInterval(blinkInterval);
}
var blinkInterval = setInterval(blinkCursor, 500);
Also, don't pass setTimeout
/setInterval
a string, pass it a reference to the function instead.
Upvotes: 3
Reputation: 1430
Your problem is that your JavaScript is executing before the HTML is interpreted - the DOM has not loaded.
While I'd recommend that you use something like jQuery to ensure document readiness, here's your problem solved without it:
<script type="text/javascript">
function blinkCursor() {
var blinkObj=document.getElementById("blink");
blinkObj.style.display = (blinkObj.style.display == "none")? "inline" : "none";
setTimeout("blinkCursor()",500);
}
setTimeout("blinkCursor()",500);
</script>
Upvotes: 1
Reputation: 70487
You need to either use an onload
event or put the script inline in the body, and after the element. This is because when Javascript in the <head>
is loaded, the full DOM isn't available yet, so it can't see elements.
Upvotes: 4