JavaScript Chapter 2 The Browser

A First Javascript

Fire up whatever text editor you're comfortable with. For us, we're going to be using Notepad on a Windows machine. Add the simple HTML you see below:
HTML code for a basic web page
So we have the HEAD and BODY tags of a HTML page, along with a TITLE area at the top. Save your text file with the name first_script.html. If you're using Notepad then you need to change theSave As Type area at the bottom to All Files, otherwise you'll end up with a text file rather than a HTML page that you can load into a browser. (You don't need to do this if you're using TextEdit on a Mac. Just type first_script.html in the Save As box.)
The Save As dialogue box
We now need to add some Javascript tags. In between the two BODY tags, then, add the following:
Script tags added to the body section of a  HTML page
The lines you're adding are these:
<SCRIPT LANGUAGE = "Javascript">
alert("Hello World")
</SCRIPT>
Programming scripts are added between two <SCRIPT> tags, an opening one and a closing one. An attribute to the SCRIPT tag is LANGUAGE. This tells the browser which scripting language is being used. For us, this is Javascript. This goes after an equal sign ( = ). Notice that we've surrounded the word Javascript with double quote marks. But you don't have to. In fact, you can miss out the LANGUAGE attribute altogether and just have this:
<SCRIPT>
alert("Hello World")
</SCRIPT>
Any Javascript you want to add needs to go between the two SCRIPT tags. Careful of the forward slash for the end SCRIPT tag - miss this out and your code won't work. Like all HTML tags, though, the two SCRIPT tags can be lowercase, if you prefer:
<script>
alert("Hello World")
</script>
However, although the SCRIPT tags are not case sensitive Javascript very definitely is. Our code consists of a single line, a simple alert box. All it does is to display a dialogue box with the words "Hello World". Try it out. Save your work. Now use Windows Explorer or Finder on a Mac to navigate to where you saved the HTML file. Double click to run your script in a browser. You should see the following in Firefox:
A Javascript alert box in Firefox
Or this in Internet Explorer:
A Javascript alert box in Internet Explorer
Now change your alert line to this:
Alert("Hello World")
The word alert now has a capital "A". Save your work and reload the page in your browser. You should find that the alert box no longer displays. Change it back to a lowercase "a", save and reload. The alert box will come back.
Alert Boxes are used to display information to your users. In between a pair of round brackets, you type the text you want people to see. This text goes between quote marks (single or double quotes, but not a mixture of the two).

Confirm and Prompt

As well as an alert box, you can have a confirm and a prompt box. Using a confirm box will get you two buttons, OK and Cancel. They are normally used with an IF Statements to detect which of the two buttons was clicked. You'll learn about IF Statements in a later section, but the code for a Confirm box is just this:
confirm("OK or Cancel?")
Again, the text you want to display goes between quote marks. In a browser, the confirm box looks like this:
A prompt box is used when you want some input from the user. The code for a Prompt box is this:
prompt("Favourite Colour?", "Red")
The prompt box has two parts between the round brackets. The first part is the heading, while the second part is some default text. Here's what they look like in a browser:
A user can enter some text in the text box. When the OK button is clicked you can get at the text the user entered and do something with it. You'll see how to do this in the IF Statements section.
For both confirm and prompt boxes lowercase letters are used.

Javascript Tag Placement

In Javascript, SCRIPT tags can be inserted into three places: in between the two BODY tags, in between the two HEAD tags, and as a link to an external file, also in the HEAD section.
Some advocate putting the SCRIPT tags in the BODY section, right at the end. Like this:
Javascript tags in the BODY section of a HTML page.
The reason to do it this way is because the web page itself will have loaded before the script is read. If it's in the HEAD section, the script will be parsed before any HTML or CSS elements are loaded. If your Javascript references any of the web page's elements, there may be a slight delay in the fancy effects you want to apply, or it may just not work at all.
For the most part, though, we'll place our script tags in the HEAD section of the HTML. Like this:
Javascript tags in the HEAD section of a HTML page.
Exercise
Using your code from the previous lesson, move your Javascript code from the BODY to the HEAD section of your HTML, so that it looks like ours above. Change the confirm box back to an alert message.

External Javascript Files

Javascript code can also be placed in an external file. Your SCRIPT tags then include a SRC attribute that points to the location of your Javascript file. Here's the HTML:
An external Javascript file reference.
In the code above, we have added the following attribute to the opening SCRIPT tag:
SRC="scripts/external_javascript.js"
SRC stands for Source. After an equal sign, you type the path to your Javascript file. We created a folder called scripts. Inside of this folder we placed a file called external_javascript.js.
Note the new extension - js. When saving code in an external file, end the file name with the two letter extension js.
The file itself is this:
Code in an external Javascript file.
All we have here is the alert box line. Notice that we don't need any SCRIPT tags in the external file. That's because they are already included in the HTML code. When the browser parsers the HTML it sees the SRC attribute and then includes all your Javascript at that point.
When your code gets too long and unwieldy, placing it in an external file helps you to control it more. Plus, if you need to make changes to the Javascript you'll only need to amend one file, instead of making changes to the HEAD section of lots of HTML files.
Exercise
Move your alert message to an external file. Make sure you get the file referencing part right after the SRC attribute, otherwise your code won't run properly.

The Browser Object Model

All browsers are split into different parts (objects) that can be accessed using Javascript. Collectively, these parts are known as the Browser Object Model, or the BOM. At the very top of this browser hierarchy is the Window object. This represents the entire browser, with its toolbars, menus, status bar, the page itself, and a whole lot more besides. Effectively, the Window IS the browser.
Underneath the Window Object there are lots of other objects you can access. These allow you do things like, redirecting the user to a different web page, get the size of the browser window, access all the HTML elements on the page and, again, a whole lot more besides. Here's an (incomplete) list of Window objects. Notice that the two objects are separated by a dot (full stop/period), with no space between the two.
window.document
Allows you to access all your HTML elements. We'll go into more detail about the document object later.
window.history
Access information about browsing history. This object is of limited use since you can't get at which pages a user has visited, just how many pages are in the browsing history. You can also access the methods history.back, history.forward and history.go. There's not many situations where you want to, though.
window.innerHeight and window.innerWidth
Gets the height and width of the available space on the page
window.screen 
Gets information about the browser screen.
You may think that screen is the same as innerHeight and innerWidth but they are not. As an example, create a new HTML page from your template with SCRIPT tags in the HEAD section. Now add the following Javascript:
So it's just an alert box with window.innerHeight between the two round brackets. Previously, we had text in between the round brackets surrounded by double quotes.
Save your page and load it into your browser. When the page loads, you should see this:
The 908 in the alert box means 908 pixels worth of height. Yours may well be different. It depends on how big your monitor is, and how many toolbars you have in your browser. The alert box above is from Firefox. Here's the same web page in Internet Explorer version 9:
Our Internet Explorer has no toolbars, just the address bar at the top, so the number of pixels is greater.
Now reduce the size of your browser. In windows, you can click the Restore Down icon to do this. (The Restore Down icon is just to the left of the red X in the top right.) Mac users can resize with the mouse pointer held over the bottom right of the browser.
Refresh your page by hitting the F5 key on your keyboard. Your innerHeight value should change:
Now change your alert box code to this:
alert( window.screen.height )
This time, we're using the height value of the screen object. Save your work and refresh. No matter what size you have the browser, you should see the same screen height:
For us, the screen height is 1080 pixels. It will remain 1080 pixels whether we have a big browser size or large browser size.
So if you're trying to get the available size that a web page has, you should not rely on the window.screen objects.
window.navigator
Used to gets information about the browser. The navigator object exposes lots of other objects you can use. For example, there's this one:
window.navigator.cookieEnabled
If you put that between the round brackets of an alert box it will tell you if cookies have been enabled in your browser. This is usually used in an
IF Statement, though. If the answer is yes, then a cookie can be set on a user's computer. If no, then you can ask people to enable cookies.
Other navigator objects are:
appName
appVersion
language
platform
userAgent
Try them out in an alert box and see what they do. You can't rely on the first two, however. appName, for example, will return Netscape in Firefox and Safari. You can use userAgent to detect if someone is surfing your site with, say, an iPad. The userAgent will say something like:
"Mozilla/5.0(iPad; CPU OS 5_0_1 like Mac OS X)"
window.location
You can do some quite advanced stuff with the location object, but the main use of location is to redirect a user to another web page. For example, if you detected someone was using an iPad then you can redirect them to your iPad optimised page. The location object is used like this:
window.location = "http://www.homeandlearn.co.uk/";
After an equal sign, you type the name of the web page or site that you want your visitors to go to. This needs to go between quotation marks. Notice the use of a semicolon at the end of the line above. This is not strictly necessary. But it is recommend that you separate each line of code with a semicolon. We'll be doing that from now on.

Window Methods and Events

The Window object also has something called Methods. A method is a chunk of code that does a particular job. The alert, confirm, and prompt boxes you have been using are methods. If we were being exact we would have written this:
window.alert("Alert Message")
And this:
window.confirm("OK or Cancel")
But because the Window object is a Global object you don't have to use window "dot" notation. You can just type the part after window. For clarity's sake, though, it's better to keep the window part wherever possible as it's clearer to you what your code means.
Other window methods that are commonly used are these:
window.clearInterval
window.clearTimeout
window.close
window.open
window.print
window.setInterval
window.setTimeout
The first two and the last two or used to set up and manipulate timers. Timers are very useful in animation. We'll explore animation much later. The close and open methods do what you'd expect them to do - close a window and open a new one. The print method brings up an Operating System's print dialogue box. Let's have a look at the window.open method more closely.

window.open

It's quite useful to be able to open up a new window from the current page. For example, we use it on our site for the "contact us" links. The new window then contains things like email address, phone numbers, etc. The new window typically opens when you click a hyperlink on a web page. You can also have a window open when a web page loads, so-called popup windows (which can be very annoying for your visitors).
The code below illustrates how to open up a new window when a hyperlink is clicked. Don't worry about understanding this code yet, as it's a bit complicated at this stage of your programming career. But it uses something called a function. The function is called into action when the hyperlink is clicked. You'll study functions later in this course. Here's the code, though:
That part that opens and configures the new window is this (it's only on three lines above so as to fit on the page):
window.open("popup.html", "PopUp", "toolbar=no,width=500,height=300");
In between the round brackets of open are three thing: the page you want to appear in your new window (popup.html for us), then a name for your new window (PopUp, but it can be just about anything you want), and finally the configuration options for the window. We have three configuration options: one to set the toolbar to no, one to set the width of the window, and one to set the height. All the configuration options go between a set of quotation marks, with no spaces between each option and its value. All three options are separated by commas.
Here are some more configuration options you can have:
left - the left position of the window in pixels
top - the top position of the window in pixels
height - height of the window's viewing area. Minimun height is 100 pixels
width - width of the window viewing area. Minimun width is 100 pixels
menubar - gets you the File, Edit, View, etc, menus at the top.
toolbar - gets you the standard toolbar: back, forward arrows, etc
location - gets you the Address bar, to type web address in
scrollbars - gets you scroll horizontal and vertical scroll bars
If you don't list a feature above then it is turned off by default. In our code above, we didn't need to say "toolbar=no" because "no" is the default.

window.alertwindow.confirmwindow.prompt
You have already used these dialogue boxes. But just take note of the fact they are methods of the window object

Window Events

When we opened a new window above, we did so from a hyperlink between the two BODY tags. The hyperlink text was this:
<a href="#" onClick="eAdd()">Link Text Here</A>
The onClick part is something called an event. Lots of other objects between the two BODY tags can use the onClick event. For example, a button on a form, check boxes, drop-down lists, images - in fact, just about anything between the BODY tags. But the idea is to call some Javascript code into action when the event takes place.
There are lots of window events you can use. You can probably guess what most of them are used for.
onChange
onClose
onKeydown
onKeypress
onKeyup
onLoad
onMousedown
onMousemove
onMouseout
onMouseover
onMouseup
onScroll
onSelect
onSubmit
onUnload
We won't go through the whole list just yet, but you'll meet quite a few of these events throughout this course.

Document Object Model - the DOM

The Document is another Window object you can manipulate. It's quite a powerful object as it refers to just about all the elements you can have on a web page (forms, links, images, text, HTML code, etc). This means that you can use Javascript to get at HTML elements, amend them, and add new ones. This is quite advanced stuff, however, and we'll only go through a few of the document objects in this beginner's book. But to get an idea of just how many document properties and methods are available, have a look at this page:https://developer.mozilla.org/en/DOM/document. Whole books have been written on the subject!
One really useful document method is write. We'll take a look at that now.

document.write

The document's write method can be used to insert text onto your web page (this text can actually be HTML elements). Try this as an example:
  • Create a new HTML web page from your template
  • Save it with the name write_method.html
  • Add the following H1 heading to the HTML: <H1>The document.write method</H1>
  • Put two SCRIPT tags in the BODY section of the HTML
  • Between the two SCRIPT tags, add the following:
document.write( window.screen.height );
(Notice the semicolon at the end of the line. We'll use them to separate each line of code from now on.)
Your new HTML page and Javascript code should look like this:
Javascript code showing the document.write method
Save your work and open up the web page in a browser. You should see this:
document.write in a browser
Instead of an alert box, we're now writing the screen height directly to the web page. (Your screen height may well be different.)
Now cut the Javascript from the BODY section and paste it into the HEAD section of the HTML. Save your work and refresh the page in your browser. You should see this:
document.write in a browser
The reason the screen height is now at the top is that the code in the HEAD section gets executed first. But the browser doesn't wait until the whole page loads - it executes the Javascript in the HEAD section first. This contained the document.write method. Because the write method writes to the page then this happens before any HTML is displayed.
Put the Javascript code back into the BODY section. Amend your code to this:
document.write("Screen Height=" + window.screen.height);
What we've done here is something concatenation. This just means joining strings of text together. We've added some direct text between quotation marks. After a plus symbol ( + ) we then have the screen height code. The plus symbol when used like this means "join together". You can use it as many times as you want. For example:
document.write("SH=" + window.screen.height + " SW=" + window.screen.width);
The SH and SW above obviously mean Screen Height and Screen Width. But note where all the plus symbols, commas and spaces are. Get your plus symbols and/or commas wrong and your code won't work.
You can use HTML tags with concatenation. For example, if you want to spread things over two lines, you can use the BR tag. Like this:
document.write("SH=" + window.screen.height + "<BR>" + "SW=" + window.screen.width);
The BR tag is surrounded by quotation marks. You need the quote marks for any HTML that you insert using the write method.
You can use document.write as many times as you want. In the code below, we have moved the SCRIPT tags back to the HEAD section. We then used document.write twice: once to add the H1 line, and once to add the text below it.
document.write used to create HTML
Try these two exercises to get the hang of document.write.
Exercise
Use concatenation with document.write to create the following in your browser:
A document.write exercise for Javascript beginners
We used document.write twice here. The first one wrote a H1 heading. The second one combined the text "Your browser is set to:" with window.navigator.language. We also have bold text for the browser language (your language may be different - it depends where you are in the world). Of course, you'll need to know what the HTML tag for bold text is!
Exercise
Use document.write to create an address like the one below:
A document.write exercise for Javascript beginners
This address is centre aligned in the browser, with the first line in bold. We used document.write seven times. Five of those seven times are for the address. The other two are used to get the centre alignment. So you start with:
document.write("<P Align=center>");
And the last line is:
document.write("</P>");
What this does is to get you a paragraph with the alignment. The other five uses of document.write are for inside of these two.

Comments