<script language="Javascript">
The language attribute is deprecated, use type instead.
if (getHours( ) = setHours(1))
OK, a few issues here: getHours() and setHours() aren't global functions, they're methods of the Date object. That means you need to create one of those first with new Date(). Secondly, the = operator in Javascript is purely for assignment. When you say a = b it means "let a equal b," not "a equals b." Comparison is done with the === operator.
if (getHours( ) = setHours(1))
{ document.write('It is 1 OClock A.M.;')
}
if (getHours( ) = setHours(2))
{ document.write('It is 2 OClock A.M.;')
}
if (getHours( ) = setHours(3))
{ document.write('It is 3 OClock A.M.;')
}
// &c.
OK, so first principles of programming: if you're repeating yourself that much, you're doing it wrong. In this case, you should just insert the number directly into the output.
Keeping it simple because you're new:
Code:
<script type="text/javascript">
var d = new Date(),
hours = d.getHours(),
meridian = hours > 12;
hours %= 12;
if(meridian) {
meridian = "P.M.";
} else {
meridian = "A.M.";
}
document.write("It is " + hours + " " + meridian + ".");
</script>
Now, document.write() isn't really a good idea; it's non-standard nowadays, and (as you noted) destroys the document if you call it at a bad time. So, instead, let's create an element to which our script can output and use that instead:
Code:
<p id="clock"> </p>
And adapt our script to modify that:
Code:
<script type="text/javascript">
var d = new Date(),
hours = d.getHours(),
meridian = hours > 12 ? "P.M." : "A.M.",
outputElement = document.getElementById("clock");
hours = (hours % 12) || 12;
outputElement.firstChild.nodeValue = "It is " + hours + " " + meridian + ".";
</script>
Now, this fails if you have the script before the element in the script, because when the script is run, it hasn't been created yet. So instead of running it immediately, we can make it into a function and tell the browser to run it when it's finished loading the document:
Code:
<script type="text/javascript">
window.onload = function() {
var d = new Date(),
hours = d.getHours(),
meridian = hours > 12 ? "P.M." : "A.M.",
outputElement = document.getElementById("clock");
hours = (hours % 12) || 12;
outputElement.firstChild.nodeValue = "It is " + hours + " " + meridian + ".";
};
</script>
You probably won't understand most of this yet, but that's OK: get reading and come back if you have questions
Bookmarks