A First Javascript
<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:
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:
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:For both confirm and prompt boxes lowercase letters are used.
Javascript Tag Placement
Some advocate putting the SCRIPT tags in the BODY section, right at the end. Like this:
For the most part, though, we'll place our script tags in the HEAD section of the HTML. Like this:
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:
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:
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
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:appVersion
language
platform
userAgent
"Mozilla/5.0(iPad; CPU OS 5_0_1 like Mac OS X)"
window.locationYou 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
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.clearTimeout
window.close
window.open
window.print
window.setInterval
window.setTimeout
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:
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.alert, window.confirm, window.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.onClose
onKeydown
onKeypress
onKeyup
onLoad
onMousedown
onMousemove
onMouseout
onMouseover
onMouseup
onScroll
onSelect
onSubmit
onUnload
Document Object Model - the DOM
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:
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:
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.
Exercise
Use concatenation with document.write to create the following in your browser:
Exercise
Use document.write to create an address like the one below:
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
Post a Comment