Chapter 2: Start me up!
Ok, now that we have gotten the history and basic know how out of the way, it's time now to finally do some scripting. In this chapter I will show you where to place your scripts and later use them as external files linked to your HTML page, plus adding comments in your scripts for future reference and for anyone wanting to find out more information about your scripts. Also you'll be learning the redirection script that will automatically change a page to another page. But for now let's get started!
The chart below will show the basic HTML tags I will be using and that you should already be familiar with, if not then please go to my HTML/CSS Basics Tutorial to review the basics of HTML and CSS before continuing.
Tag | Attribute | Description |
---|---|---|
html | The page used to hold all the coding | |
head | Holds the header part of the page | |
script | This holds scripts and external scripts such as JavaScript, CSS, but not always | |
src | This the link to the external script | |
title | Here is where you title the HTML page you are working on | |
body | Here is where you place divs, classes, attributes, and tables | |
h1...h6 | These are your headers which work in a priority format starting with header 1 being the largest and to header 6 being the smallest | |
a | Used to link to other pages or can be assigned to link to other parts inside your web page | |
href | Directs the user to the link when the link is clicked on | |
id | The id is assigned to the link |
Where to Put Your Scripts
Your scripts can exist in two areas of the HTML page, either between the header tags <h1> and </h1>, or between the body tags <body> and </body>. For this example we will put it in the body tag.
This script also needs a container with a tag name <script> and </script>, and this is where we will write our first javaScript code. The example below will first show the full HTML layout and then there will be a link to view the result.
Note: The language and type attributes of the script
tag (which I'm not using here) have been deprecated, which means that the W3C, the standards body responsible, has marked the attributes as one that will not necessarily be supported in future versions of the standard. There are plenty of older scripts that still use it, though.
Note: Using a semicolon at the end of a JavaScript line is optional, so long as you only have one statement per line. I've included them in this tutorial for clarity, and I suggest that you get into the habit of including them in your code for the same reason.
Note: You are allowed as many script
tags (and therefore, multiple scripts) on a page as you'd like.
My First Script | |
---|---|
Your script should look like so: | |
<!DOCTYPE html> <html> <head> <title>My first script<⁄title> <⁄head> <body> <h1> <script> document.write("Hello, World!"); <⁄script> <⁄h1> <⁄body> <⁄html> |
"Hello, World!" |
About Functions
Adding scripts within your HTML page is pretty straight forward like what we did just above, but now it is time to move on and try a new approach using an external file to display the same message. First we should discuss about functions because functions are very important when using external JavaScript files.
A function can be used as many times as you need while the script reads through the document. For example this is very useful for forms that need filling out more than once or you may need to recall backed up images. Well instead of writing out a script each time, you can just write a function that can be given an id then can be recalled over and over again.
The anatomy of the function consists it's name "function" followed by giving the function an identifiable name like "saySomething". Note: it's very important that you not have any spaces or numbers that are in the front. After the name, you should have parentheses followed by an open brace "{". The statements which make up the function then go between the braces, then adding a semicolon will allow you to add more statements, but for now we will finalize the function by closing it with a closing "}".
The whole function should look something like this:
function saySomething() { alert("Four score and seven years ago"); }
Using External Scripts
Now you will be using an external JavaScript file and linking it. First you will make a new JavaScript file within the application your using, for instance, I'm using Dreamweaver to build my pages. Name the script associated with your HTML page or hello world, and save it into a folder called (.js). Then link the file by placing it under the title inside the header section. It should look something like this: <script src="lib⁄js⁄chapter2.js"><⁄script>. After it has been linked, then you will create the actually "id" to direct the script in the right direction to run the function. This should look like this: <h1 id="helloMessage"><⁄h1>.
My Second Script | JavaScript Code |
---|---|
Your code should look like so: | Your code should look like so: |
<!DOCTYPE html> <html> <head> <title>My second script<⁄title> <script src="script02.js"><⁄script> <⁄head> <body> <h1 id="helloMessage"><⁄h1> <⁄body> <⁄html> |
window.onload = writeMessage; fuction writeMessage() { document.getElementById("hellowMessage") .innerHTML = "Hello, world!"; } |
JavaScript code explanation
window.onload: This is known as a event handler, which will be explained later.
writeMessage: The writeMessage comes after the equal sign indicating the functions name. This is basically saying that the window has finished loading and tells the writeMessage to run the function.
function writeMessage() {: This line starts the writeMessage() function.
document.getElementById("hellowMessage").innerHTML = "Hello, world!";: This section is where the script actually searches for the message by locating it in the HTML page under it's identity "hellowMessage", then the script reads it as if you were reading the directions from right to left, so it's actually reading it as "Take the string 'Hello, world!' and place it into the document, inside the element on the page which is named "helloMessage". This would be equivalent to writing it by hand in your HTML file, but the only difference is that you wouldn't need to repeat it over and over again.
Note: Most newer browsers such as Chrome, Firefox, and Safari all support JavaScript, and Microsoft Internet Explorer 4 and later, and Netscape 3 and later, support JavaScript as well.
Note: In most cases developers prefer to use external scripts because it frees up room in their HTML document and is tucked away in the backgrounds, but user who is technically savvy enough to check their browsers 's cache files-everything that the browser has seen is stored there.
Note: If you've seen the function before, you might be expecting the writeMessage reference in the example above instead be writeMessage(). It's not, because the two mean different things: a function shown with parentheses means that the function is being called, right then and there. When it's without parentheses (as it is here), we're assigning it to the event handler, to be run later when that event happens.
Putting Comments in Scripts
As a good rule of thumb, it's always a good habit to add comments as you create your HTML, CSS, and JavaScript codes because it's useful for both you and your user.
There are two ways to display your comments in your JavaScript. If you want to have just one line of information, then it would start like this: //, but if you need to add multiple lines, then it would start with: /* and end with */ to complete the comment.
COMMENT EXAMPLE:
// Here is a comment example for just one line of information.
/*
Here is a comment example
for a multiple line of information.
*/
Alerting The User
As you have already noticed when you came to this page, a message pops up reading, "Welcome to my tutorial, so sit back and enjoy the ride!". This means that your browser is able to read JavaScrip, if it didn't pop up, then you should see this message that reads, "This page requires JavaScript." and means that you either have to activate in the preferences or it just doesn't support it. Hopefully you should never have to see this, other than if you are using a really out of date browser.
My Second Script | JavaScript Code |
---|---|
HTML NoScript script message | Message that appears on the onload window script code |
<!DOCTYPE html> <html> <head> <title>My JavaScript page<⁄title> <script src="script04.js"><⁄script> <⁄head> <body> <noscript> <h2>This page requires JavaScript.<⁄h2> </noscript> <⁄body> <⁄html> |
window.onload = writeMessage; alert("This page requires JavaScript.") |
This page requires JavaScript. |
---|
Code explanations
The first box with the HTML code setup will be hidden in the background unless it needs to be called up because of a non-JavaScript browser, but this is how it should be coded.
The second box demonstrates the JavaScript code for the Alert message and how it should be written as illustrated below.
window.onload = initAll: This initiates the JavaScript process for the window that will be displaying our message.
alert("This page requires JavaScript."): The word Alert is our method and your phrase goes between the parentheses and inside quotes. So now whenever the page loads, this should be the first thing that accures before anything else. For fun and just for testing, try opening your page with this alert message and see what the other browser's boxes look like. Some look cooler than others and add a little extra pizzaz.
Note: Almost all browsers will show that this message was opened by JavaScript, this is another security feature to protect you from getting unwanted scripters trying to interrupt. For example Safari, Firefox, and Microsofft Internet Explorer all will show the URL of the site that opened the message, so this makes for a comforting feeling when surfing anywhere on your browsers when others use this alert.
Confirming a User's Choice
Ther are times that you want to give your user choices that they can activate and get a response or a result in figures. The links below will take you to a new page that will give you some interesting and fun results, so give them a try and after your done I will explain what took place so you don't freakout when you see all these boxes pop up. I admit it brings out a little bit of anxiety in me when ever I see a bunch of these unknown boxes pop up, so I will be there to guide you on your way:)
These scripts also introduce what we call conditionals, which simply means that the script poses a test and performs action in different states, but it will change depending on the choice. You can almost think of it as the old school "Choose Your Own Adventure" series where you would read the story and then come to an area where you would choose whether you open the door, or climb out the window, or make left turn or right turn. Either way the choice you made, changed the out come of the story. I know this is a little stretched but hopefully you'll get the point when you see the explanation.
About Conditionals
Conditionals can be broken down into three parts: if, is where we do our test; then, is where we put the script that will have the result of being true; and finally we have the optional else, is where we put the script that will have the result of being False. The section with the if part are in parentheses, and the section with the other two parts are in the braces.
1 |
if (confirm("Are you sure you want to do that?")){ |
---|---|
The confirm() method uses one parameter, and the other parameter will include the question: ("Are you sure want to do that?") and then resturns to either True or False depending on the user's choice. |
|
2 |
alert("You said Yes!"); |
If the user chose OK button, confirm() returns true, and then an alert displays, saying "You said yes". If you noticed this would be the then section of the code, even though there's no then operator in JavaScript. The braces as the delineation of the then area. |
|
3 | |
4 | |
5 | |
6 | |