Andy's JavaScript tutorial 2
Dynamically
changing the document's background color
Ok, let's begin by seeing how to change the background color of the
document using JavaScript. Take a look:
<script>
document.bgColor="blue"
</script>
You can change blue to any color name, or the color's hex representation
(ie: #000000).
This is a very simple illustration of JavaScript at work; changing the
background color isn't exactly something good-old HTML can't do easily all by itself.
However, this is just the beginning of our JavaScript journey...have some patience!
Status bar messages
Using JavaScript, you can display messages in the status bar of your browser below.
This is accomplished by setting a string value to the "window.status" property.
For example:
<script>
window.status="Welcome to my homepage"
</script>
By doing the above, the message "Welcome to my homepage" is shown in the
status bar. One trick you may have seen on the web is a status bar message that is
initiated only when the user moves her mouse over a link:
Yahoo
Here's the code used:
<a href="http://www.yahoo.com" onMouseover="window.status='Click here
for Yahoo!';return true" onMouseout="window.status=''">Yahoo</a>
I captured the mouse's "position" by using the onMouseover and
onMouseout event handlers of JavaScript. Event handlers are added directly inside certain
HTML tags such as the <a> tag, and allows you to run code that react to a certain
event (such as when the mouse moves over a link). In this case, the code displays
"Click here for Yahoo!" in the status bar when the surfer moves her mouse over
the link "Yahoo", and resets the status bar when the mouse moves out. Pretty
cool, uh?
On-the-fly
text
Text inside the document is usually static- if you reload this
document 5 times, there's no reason to believe that the document's text will be any
different each time...or is there? One of the coolest things about JavaScript is that it
allows you to generate text on the fly. You could, for example, have the document greet
you "Good morning" in the morning, and "Good night" at night. The
basic way to write out text in JavaScript is by using the document.write() command, as
follows:
<script>
document.write('Some text')
</script>
Whatever you put inside the parentheses, JavaScript displays it
on the page. Taking this basic idea one step further, I'll create a script that writes out
the last modified date of this page.
<script>
var modifieddate=document.lastModified
document.write(modifieddate)
</script>
The above is a perfect example of "on-the-fly" text. The text
reflects the last modified date of your page, and is updated automatically whenever
you edit the page and save it!
Andy's Tutorial 3>>
|