Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

JavaScript Tutorials The Document Object (Part One) That Document Thing As was mentioned, document is a part of the

Document Object Model. We saw a method that can be used with document, but here's a couple more (Properties and Methods). Properties

y bgColor y fgColor y title y location y images y forms


Methods

y open() y close() y write() y writeln()


There are quite a few more Properties and Methods you can use with document, but these are enough for us. Let's see how you can use them in your own scripts. Start a new web page in your HTML Editor (Or use an old one, if you like - waste not, want not!) Then add this to the BODY section of your page: <BODY> <INPUT TYPE = Button VALUE = "Colour One" Onclick = "document.bgColor = 'Red'"> <INPUT TYPE = Button VALUE = "Colour Two" Onclick = "document.bgColor = 'Blue'"> <INPUT TYPE = Button VALUE = "Colour Three" Onclick = "document.bgColor = 'Green'"> </BODY> Remember, when you're typing the OnClick code that this bit "document.bgColor= " is surrounded by double quotes, and this bit: 'Green' is surrounded by single quotes. And the whole thing is a confusion of single and double quotes: Onclick = "document.bgColor = 'Green'" When you're done, save your work and view the results in your browser. Click the button and see what happens.

Well, how did you get on? That should impress the neighbours, hey? If it doesn't, you have some very strange people living nextdoor to you. Try moving house until you find some neighbours who are impressed. The background colour of your web page should have changed colour when you clicked a button. It did this because of the bgColorpoperty of the document object. document.bgColor = After the equals sign, you can either type a name of a colour, or better use an Hexadecimal value: document.bgColor = #FF0000 document.bgColor = #0000FF document.bgColor = #00FF00 The fgColor property is similar to the bgColor property. Except it will change the colour of any foreground text on your page. Try it out and see how it works. You only need to change the "b" of "bgColor" to an "f". And type some text.

The document Title Property

The Title of a web page appears at the very top of the browser window. You set it by typing some text between the two <TITLE> tags. You can use JavaScript to either get the Title or to set a new one. Here's a script that pops up the Title in an alert box. Try it out and see it in action: <HTML> <HEAD> <TITLE>The title of this web page</TITLE> <SCRIPT LANGUAGE = JavaScript> alert(document.title) </SCRIPT> </HEAD> <BODY> </BODY> </HTML> You can also reset the title of the web page. Change you alert code to this: alert(document.title = "Now I've changed it") The equals sign in there doesn't actually mean equals. It means "assign the value". So what we're saying is "Assign the value of 'Now I've changed it' to the title of the document." Any direct text that you type after the "assignment operator" (the equals sign) needs to go inside double quotes. Load up your new code in your browser, and watch what happens. First, you'll get an alert box: Netscape/Mozilla Alert Box

Internet Explorer Alert Box

But that's not the only thing that happens. If you look at the very top of your browser, the title should have change from "The title of this web page" to "Now I've changed it." Here's the changed version in the two most popular browsers:

Now that you're an expert with alert boxes, here's a little exercise.

Exercise

Use an alert box to test out the location property of document.

A JavaScript Rollover

For this part, you may need these two images. Right click on the images, and save them to your own computer:

Now we can begin.

A useful property of document is images. The images property tells you if any images are loaded. If the answer is yes, and your HTML images have a NAME attribute, document.images can gain access to them. Why is this useful? Well, let's see. Examine this HTML code for an image: <BODY> <IMG SRC = "pointer1.jpg" NAME = "but1"> </BODY> Simple enough, because it's just standard HTML Image code. We can turn the image into a link by surrounding it with an Anchor tag: <BODY>

<A HREF = "page2.html"> <IMG SRC = "pointer1.jpg" NAME = "but1" Border = 0> </A> </BODY> Still, simple enough: now we've just added the HREF tag and switched the borders off in the image. However, we can add a bit of JavaScript to the Anchor link. This bit of JavaScript uses the images property of document. Like this: <BODY> <A HREF = "page2.html" OnMouseOver = "document.images.but1.src= 'pointer2.jpg'"> <IMG SRC = "pointer1.jpg" NAME = "but1" Border = 0> </A> </BODY> That code looks a bit messy spread over two lines. Notice, though, what was added to the HREF code. It was this: OnMouseOver = "document.images.but1.src= 'pointer2.jpg'" Remember the OnClick event of the button you did? Well, OnMouseOver is another event you can use. This event does something when the user places the mouse over a link, or an image, or whatever. After the equals sign (assignment operator, if you please), we write the code (not forgetting all those awfully messy double and single quotes): "document.images.but1.src= 'pointer2.jpg'" See what we're pointing at? The document.images part is pointing to our image that has the NAME but1. We're then saying access the SOURCE (src), and change it to 'pointer2.jpg'. To see the effect that all this code has, move your mouse over the image below. Move it away and then back again.

Neat, hey? Are the neighbours impressed yet? Blimey, they're a tough crowd. The code for the "dancing hand" uses an event related to the OnMouseOver event - the OnMouseOut event. The code is then exactly the same, except you're resetting the image back to pointer2: OnMouseOut ="document.images.but1.src='pointer2.jpg'"

So by using the images property of document you can create a rollover effect. This is not, however, the recommended way to create a rollover. The standard way is to pre-load the images in the head section of the web page, then use something called a function to switch the images around.

Another property of document is forms. We're going to use the Form property of document to validate user input. For that, we need to delve a little deeper into the JavaScript, so we'll leave it till The Document Object (Part Four) JavaScript Methods and Events

Let's have a look at those document Methods. They were: open( ), close( ), write( ), writeln( ). We've already done write( ), and writeln( ) is the same as write( ) except that you get a line break. So we'll look (briefly) at open( ) and close( )

open( )

We're not going to be using this method, but for reference purposes here's what it does. The default for document.write( ) is to write stuff in the current document window - the browser window. It doesn't need to open a new window, because it already has one to work with. You can use document.open( ) to create a new document and send it things like HTML code. You could send the HTML code with document.write( ) document.open( ) document.write("<H1>Hello</H1>")

close( )

This method is used to close the document you created with the open( ) method.

Events

Two useful document Events you can use are these: onLoad = onUnload = These are typically used in the BODY section of the HTML code. Here's two pieces of code that will annoy visitors to your site:

<BODY onLoad = "alert('Welcome to my web page')"> Or when they leave your site, there's this: <BODY onUnoad = "alert('Goodbye - Have a nice day')"> We'll see another way to annoy your visitors when we create a pop-up window. We'll do that real soon. The next part will look at another object that is widely used - the navigator object.

The Navigator Object

Testing your Visitor's Browser


The document object dealt with code between the BODY tags. The navigator object is used to reveal information about the browser your visitors are using. Because some browsers can't deal with certain things (like the document.images code we wrote), the navigator object is typically used to help divert these users away from any code that they can't handle. Two Properties of the navigator object are: appName userAgent Let's use an alert box to test them out. If you don't want to open a new page for this exercise, you can just comment out any old code between SCRIPT tags. Like this: // document.open() // document.write("<H1>Hello</H1>") The two forward slashes mean "please ignore this code". Whether you decide to create a new web page, or use an old one, type this code in the HEAD section of the page: <SCRIPT LANGUAGE = JavaScript> alert(navigator.appName) </SCRIPT> If you're using Internet Explorer, you'll get this before the page loads:

Whereas, if you're using Netscape/Mozilla, you'll get this before the page loads:

Try changing the alert box to this: <SCRIPT LANGUAGE = JavaScript> alert("Your Browser is: " + navigator.appName) </SCRIPT> The plus sign (+) is used to combine things. Here, we're combining the direct text "Your Browser is:" with whatever value is returned from navigator.appName. Note that the direct text has double quotes surrounding it, and navigator.appName doesn't. Save your work and load the web page again. You should get something like this (in Netscape):

OK, so we can tell which browser our visitor is using. But there are many different versions of Netscape and Internet Explorer. An early version of Netscape won't be able to do as much as the latest version, and therefore may not be able to run our scripts. If we just use navigator.appName we won't be able to tell if our user has an early version or the latest version. To solve the problem, we can use navigator.userAgent. Change your alert box to this: alert(navigator.userAgent) Now reload your web page. Internet Explorer will give you something like this:

The part that's useful to us is MSIE 5.01. This tells us that our visitor is using Microsoft Internet Explorer version 5.01. Here's the Netscape version:

The information we're looking for is now on the end: Netscape 6 By using navigator.userAgentwe can return all of that text and store it in a variable. We'd then use a JavaScript function to strip out the bit we're looking for. An IF statement is then typically used to execute code depending on what the browser is. In the next part, we'll take a look at how to get the size of the screen your visitor is using, and take a little history lesson. The Window Object

Screen Size, the History Property


The window object is actually at the top of the DOM tree. It's the boss man of the Document Object Model. If we we're being strictly accurate, we should have been using this: window.document.write("Hello") And this: window.navigator.userAgent But for convenience sake, window is usually left off. This is because most of your code will be written in the current browser window, and not some other window that you haven't told your browser about. The window object has some other useful tricks up its sleeve, though. You can find out information about the screen your visitor is using. By using the screen Property of window, you can add Properties that screen has. Like this: window.screen.height Some other properties of screen are: width, availHeight, availWidth, colorDepth. Let's use width and height to get the size of the screen our visitors are using. After all, they might have a tiny monitor and have to scroll way to the left to see our fancy web page. We could then redirect them to another page, if they have a small monitor.

Screen Size

Copy this code into your editor. Place it in the HEAD section of your HTML. Save your work and test the script in your browser: <Script language = JavaScript> UserWidth = window.screen.width UserHeight = window.screen.height UserWidth = "Screen Width = " + UserWidth UserHeight = " Screen Height = " + UserHeight alert(UserWidth + UserHeight) </Script> The code is a little more complicated than before. But not too complicated. First, we're storing the value in width to something called a variable: UserWidth = window.screen.width A variable is a little storage area. Think of it as a little cupboard or drawer. Instead of putting socks or underwear in the drawer, you're putting text or number into it. Your little storage area needs a name (else how could you tell which drawer held the socks and which your underwear?). The variable name is UserWidth. This is a name we made up ourselves. You can use just about anything you want as a variable name. (But there are a number of words JavaScript likes to keep for itself.) To put something in your drawer (variable) you type an assignment operator (the equals sign), then type whatever you want to put into the drawer (variable). If you putting text into the variable, surround the text with double quotes: UserWidth = "This will hold a width" If you're putting numbers into the variable, don't surround the numbers with double quotes: UserWidth = 600 Or you can combine the two with the plus sign (+): UserWidth = "This will hold a width of " + 600 You can also put the value held in another variable into your new variable. Like we did for our code: UserWidth = window.screen.width

The value held in the last bit (width), is now stored in our variable with the name UserWidth. Then we just combine direct text with the value we've just stored in UserWidth: UserWidth = "Screen Width = " + UserWidth Finally, we combine the two variables in an alert box: alert(UserWidth + UserHeight) When you load your web page, you should see a message box like this one:

Exercise

Use availHeight, availWidth, colorDepth to find out the available height of your own screen, the available width of your own screen, and the colour depth of your screen. Display the results in an alert box like this one (Netscape):

You can start a new line by adding "\n" to the end of your variable declaration. Like this: AHeight = window.screen.availHeight + "\n"

The history object

The history object can be added to window. The history object can be used to move your user back or forward. The result is exactly the same as clicking the Back and Forward buttons on the browser toolbar. You can also use history.go() to move your users a specified number of pages either backwards or forwards. The history object works like this: <Script language = JavaScript> alert("Sorry, this page is under construction")

window.history.back() </Script> That script could go in say page2.html. On page1.html, there might be a link leading to page2.html. When the link is clicked, the above script will be executed in page2.html. The results is that first the alert box displays. Then the second line of code gets executed. This uses the back() method of the history object to take the user back to where they came from. The forward() method the same way, except your user will be taken forward one page in the browsing history. To use the go() method of the history object, just type a number in between those two brackets. Like this: window.history.go( -2 ) The minus two means back two pages. To go forward, just remove the minus sign (-).

OK, we've explored a fair bit of the Document Object Model. You should, by now, have a good idea of what can be done with it. To do anything more, though, we're going to need to delve a little deeper into the JavaScript language. So a word of warning - programming starts here!

You might also like