JavaScript is object -based. This means that we work with objects and their properties.
A page is an "object" (a document object).
The page object has a background color, that's one of the page "properties".
We can change that property. Let's try this in a script!
Paste this in the head section of a page.
<script type="text/javascript">
<!--
function changeBg(myColor){
document.bgColor=myColor
}
// -->
</script>
Make a text link and enter this in the URL box:
javascript:changeBg('red')
Make a few more links that sends values like "green" and "blue".
Test your links. Cool!
Now it's time to take a look at the boring syntax. I will use a slightly more complicated example this time, a form.
The form is called "orderForm" and the text field is called "total"
<script type="text/javascript">
<!--
function changeField(someText){
document.orderForm.total.value=someText
}
// -->
</script>
The line "function changeField(someText){ " is nothing new to us, we have declared a function and set it up to receive a text string from a link.
Now comes the interesting part! Please note the similarities with the file system on your computer!
document.orderForm.total.value=someText
We start at the top, which is the "document", then we travel downwards in the hierarchy to the form "orderForm", the next stop is the text field called "total" in the form. The last thing this line does is assigning the value of the variable "someText" to the field. That value will be displayed immediately.
Paste the script in the head section of a page.
- Add a form and place a text field in that form.
- Name the form "orderForm" and the text field "total".
- Now make a few links that looks like this in the GoLive link inspector URL box:
javascript:changeField('Nate has a wombat')
- Use different texts in all links.
When your links are clicked they should now display different messages in the text field!
This technique can be use to change just about anything in a HTML page, you just have to figure out what the object is, the name of the property and what value you want to assign to it.
One last thing - you might ask yourself why we don't start at the very top of the hierarch, at the "window" level. It's very simple, as the "path" to almost all objects start with "window" JavaScript is nice and let's us omit the word "window".
Back to tutorial index <<
|