2dwebdesign.com
FREE HTML TEMPLATES
Javascript Tutorialby Boris Mordkovich INTRODUCTION As I got farther into web development I wanted to go beyond the limitations of HTML. HTML cannot make decisions, be very interactive, or store information. Javascript was the answer. It was developed by Netscape and was originally called LiveScript. The name was later changed to show the relation to Java. Now it is supported by both of the most popular browsers, Microsoft Internet Explorer and Netscape Navigator. Note: Parts of this tutorial assume you know
HTML. If you do not, consider reading this tutorial on HTML first.
This tutorial is lengthy but very thorough.
CONTENTS Part 1 - Defining a Script Part 1 - Defining a ScriptThere are 3 places you can define a script.
When defining scripts in the head and body of HTML documents
you are required to use a script tag, while if you are defining
a script within an event handler, this tag is not required. THE <script> TAG When defining scripts in the head and body of
HTML documents you are required to use a script tag, while
if you are defining a script within an event handler, this
tag is not required. JAVASCRIPT VERSIONS
OLDER BROWSERS To hide your scripts from older browsers you
can enclose them with comments (just the script, not the script
tag).
<script language="Javascript"> <!-- your script here // --> </script> You can also include the <noscript> tags to display content for visitors with browsers that don't support Javascript. JAVASCRIPT COMMENTS You can use comments for the same things you
use them in HTML, to include notes to remind you of the purpose
of certain parts of the page. There are two ways to include
comments. Part 2 - Creating a Simple ScriptIn this section you will be creating a script to ask the user for his/her name and then write it to the page. This section isn't meant to teach you much about Javascript, but it is aimed more as an introduction so you can see the basics of Javascript. GETTING THE USER'S NAME To get the user's name
we must use the prompt() method.
We will enclose the prompt within a function and execute the
function once the page loads. Then we will use the user's
input to print a welcome message (don't worry if this doesn't
make much sense to you at this point, it will in time). Let's
start by defining the function. It should be within the <script>
tags in the head of the page.
function getNames() { } This is a basic function. We won't get too in depth with functions here, you will learn more about them later. Let's ask the user for his/her name next. function getNames() { first = prompt('Please enter your first name.'); last = prompt('Please enter your last name.'); } This would ask the user for his/her name and then store it as the variables first and last. Also, make sure to include these inside the braces, this is necessary to make it part of the function. Now we need to make this execute when the page loads. We need to add the following to the body: <body onload="getNames()"> This will execute the function once the page loads. WRITING THE WELCOME MESSAGE Now that we have gotten
the user's name, we need to make it part of a welcome message.
You can do it one of two ways: Part 3 - Variables, Strings, and ArraysVARIABLES A variable is like a container
used for storing information. This is one of the easiest and
most often used parts of Javascript. Lets get to an example
so you can see exactly what a variable does. Types of Variables Lets talk about the
var keyword. This defines the
variable as being a global variable. It should be defined
outside any functions. Because it is a global variable it
can be used within any script in that HTML document and within
any functions. The other type of variable is a local variable.
A local variable is used specifically for a function and is
defined within that function. A local variable does not need
the var keyword.
STRINGS var
message = 'This is a test message';
Strings are variables that consist of a string of text. The variable above was an example of a string. Strings are one of the most simple kinds of variables. There are several different methods and properties of strings you should be aware of. For starters, the length property. var test = message.length; The above statement would result in the value of test equaling 22 because if you count each character in the message string you will end up counting 22 characters. var up = message.toUpperCase(); var lower = message.toLowerCase(); These two methods are used to change the case of a string. They would result in up equaling THIS IS A TEST MESSAGE and lower equaling this is a test message. You can also use substrings, or parts of strings. var sub = message.substring(0,7); The variable sub would equal This is. Notice that the indexing of the string starts at 0. If you were to put sub = message.substring(1,7) it would result in sub equaling his is. You can also get a single character, sub = message.substring(7);. Sub would equal s. You're not done yet, Javascript still has more things you can do with strings. The next thing you can do is to search for a substring. var index = message.indexOf('test'); Index would then equal 10 because the substring test starts at the 10th character. var index = message.indexOf('test', 5); This would return the same value for index but instead of starting at the beginning of the string, Javascript starts searching at the 5th character. This is great for searching for multiple occurrences of the substring. var index = message.lastIndexOf('test'); This would again return the value of ten but this time Javascript searches from the end of the string backwards. You can also split strings, but we will learn about that when we get to arrays. You can also use all of the numbers these methods and properties return in mathematic calculations. We will learn about storing numbers as variables next. NUMBERS var
total = 3 + 6; Javascript is capable of mathematics. For instance, the above statement would result in the value of total equaling 9. Because the value of total is a number you can then use it later in another statement. var max = total + 3; The above two statements would result in the value of max being 12 because the value of total (9) was determined in the first statement and by adding 3 to total, it would be the same as saying 3 + 9. You will later learn that being able to store numbers in variables can be very useful. If you have a string that contains a number at the beginning of it, you can use that number in calculations. var elephants = '30 elephants in the group'; var totalElephants = parseInt(elephants); TotalElephants would equal 30. You could then use the number 30 in calculations. parseInt() gives you a whole number while parseFloat() will give you a decimal number (if a decimal is needed). This comes in very handy when you are getting variables from forms because a number can be inputed into a text field (any information in a text field is, by default, treated as a string) and then that number can be used in calculations by using parseInt() and parseFloat(). You can add (+), subtract (-), multiply (*), divide (/), round up (Math.ceil()), round down (Math.floor()), and round (Math.round()) numbers. ARRAYS var
students = new Array(6); students[0] = 'John'; students[1] = 'Sue'; students[2] = 'Bob'; students[3] = 'Billy'; students[4] = 'Jane'; students[5] = 'Jill'; Arrays are very useful and not very complicated once you get use to them. They are used to store a list of variables. Let's analyze all of the parts to this array. Students is the variable that holds this array. Notice all of the parts to the first line, the variable name students, the = operator, the new keyword, the array(), and the ;. The number 6 declares that the students array is 6 variables long, this is not necessary but is nice to include. If you need the length (the number of variables) of the array you can use students.length. On the following lines there are several more variables, all called students, but notice the brackets and the index for each and notice that the indexing of the variables starts at 0. Each of the variables under the student array are strings. You can make each of those variables strings, numbers, arrays, or objects. You can also sort arrays. var sorted = students.sort(); Sorted would then be an array that contained all of the variables in the students array but they would be in alphabetical order. Therefore students[3] and sorted[0] would both equal Billy. You can also split strings. The reason I mention this in the array section is because Javascript stores the parts of the string in an array. var message = 'This is a test message'; var parts = message.split(' '); Parts would then equal an array with 5 variables. If you were to write out what the parts array looked like, you would get the following. parts[0] = 'This'; parts[1] = 'is'; parts[2] = 'a'; parts[3] = 'test'; parts[4] = 'message'; You can also use the join() method. It is used to join all of the variables in an array into one string. By default Javascript uses a comma but you can use whatever you want. var whole = parts.join('_'); Whole would then equal This_is_a_test_message. You can also treat each variable in an array as if it weren't in an array. var students = new Array(6); students[0] = 'John'; students[1] = 'Sue'; students[2] = 'Bob'; students[3] = 'Billy'; students[4] = 'Jane'; students[5] = 'Jill'; Because each variable in the students array is a string, you can use students[0].length to get the number 4 because 4 is the length of the students[0] string. WHEN TO USE QUOTATIONS When you
use quotations largely depends on what type of variable you want or if you are
trying to define a new one. Part 4 - Testing and Comparing VariablesTHE if KEYWORD The if
keyword is one that you will use over and over again in Javascript. It is used
to test and/or compare a variable. Lets get to the example. var name = 'John'; if (name == 'Bob') I admit, this isn't a very practical use for the script. The statement is basically saying if name equals Bob write Bob Curtis. But analyze the parts of the script, the name variable, the if keyword, the parentheses, the variable to be tested (name) the == operator, the string used to test the variable, and what to do if the statement is true. OPERATORS Operators
are used to compare variables (such as the == operator above); they consist of
two groups, conditional and logical. Conditional Conditional
operators are the syntax used to compare the two variables.
Logical Logical
operators are the operators you use if you want to compare more than two variables.
Just to give you an idea
of how logical operators work, check out the syntax below. THE else KEYWORD If you are using several if statements to test the same
variable and you want to include a choice that will be executed if none of the
previous statements are true, you should use the else keyword. MORE COMPARISON This section is sort
of a miscellaneous section about comparisons.
Including More Executions for True Statements Notice that in previous
comparisons only one thing has been done if the statement
has been true, you can use a different syntax to include many
executions.
if (name == 'Bob'){ alert('Bob Curtis'); } (I know the alert() method is new, it is similiar to the prompt() method and the indentions aren't necessary but they do help to make the script a little easier to read). The main difference here is that instead of including one item to execute if the statement is true you put braces around the things you want executed. You don't have to put the braces on separate lines but it makes your script look nicer and easier to read. You can also use this method for the else keyword. if (name == 'Bob'){ alert('Bob Curtis'); }else{ alert('John Smith'); } True/False Comparisons If you need to check
a variable and do one thing if it is true and another if it
is false check out the syntax below.
(name == 'Bob')?document.write('Bob Curtis'): First, you put the comparison; second, a question mark; third, what to do if the comparison is true; fourth, a colon; fifth, what to do if the comparison is false; last, the ending semicolon. Using switch If you need to use multiple
if statements in a row to test the same variable for different
occurrences.
You can write - if (name == 'Bob') if (name == 'Sue') else you could use - switch (name){ case 'Bob': break; case 'Sue': break; default: break; } This performs the exact same thing as the series of if statements. This isn't a very practical use for switch, but you will find instances where it can become very useful. Elements of the switch statement include:
Part 5 - Loops and FunctionsLoops are pretty much what you would guess; they are used to repeat certain statements for a specified number of times. Loops can make the length of script decrease tremendously in size, thus saving you lots of time and effort. THE for LOOP For
loops are used to repeat certain statements a specified number
of times using a counter. Usually this counter is a number
and has one added to it or taken away from it each time the
loop executes. Time for an example.....
for (i = 1; i <= 5; i++){ }
Let's analyze what this script actually does. The loop is started by the for keyword and then it establishes a variable (the counter), the value to test the variable with, and how the variable is to be changed each time the loop executes and it also contains braces around the statements that are to be executed. In simpler terms, this script executes 5 times with value of i having one added to eat each time the loop executes. You use the same operators you used in the last chapter to compare values. The result of the script would be 5 messages with a line break after each. It would appear like the following. Test message #1 Test message #2 Test message #3 Test message #4 Test message #5 THE while LOOP While
loops are usually used when you don't have a counter.
var i = 1; while (i <= 5){ } This would achieve the same affect as the for loop above. Like I mentioned, you don't have a counter with while loops. THE do...while LOOP do
{ MORE ON LOOPS Starting/Stopping a Loop To stop the loop you
use the break keyword; you use the continue keyword to skip
the rest of the current statements and test the variables
again.
while (i <= 5){ if (i == 4) break; } The above is an example of the break keyword. If you notice, in this example the break is kind of pointless. It would be much easier to change the loop itself, but you get the point of how the break keyword should be used. while (i <= 5){ if (i == 4) continue; } This would skip the write statement and test the variables again. The result would look like the following. Test message #1 Test message #2 Test message #3 Test message #5 Infinite Loops Infinite loops are something
you generally want to avoid. Because the loop will never end,
it can cause problems with the browser or even cause it to
crash. Let me show you an example of an infinite loop so you
can have a general idea of how they get started. FUNCTIONS Essentially, you should
not have any problems understanding functions by now. Part 6 - ObjectsThis is most likely the largest chapter of the entire tutorial and one if not the most complicated. You might want to read it in pieces and probably more than once, especially the part on custom objects. UNDERSTANDING PROPERTIES AND METHODS You have already used
several objects but chances are you haven't realized it. You
have used several objects such as the string and array objects.
You can actually define strings by using the following syntax. USING DATES
someday
= new Date(); Setting/Getting Dates You can also set dates/times
once the date has been established. You can use the following
methods. More with Dates There are a few more things you
can do with dates, such as converting between time zones and between
date formats. getTimeZoneOffset()
- gets the offset from GMT (Greenwich Mean Time, also known as UTC) UNDERSTANDING DOCUMENT STRUCTURE You can think of document structure
as being similar to a tree because everything branches out from one
object. You have already used document.write().
write() is actually a method of the document object and document
is actually a child object of the window
object. To use the write() method you
could also use window.document.write().
(You can use document.write() instead
of window.document.write() if you are
working with a script that deals with only one window, Javascript
will assume you mean the current window if you do not include the
window object here.
WRITING TO A DOCUMENT You have already used document.write() to write to a document. You can also use document.writeIn() to write to a document and include a newline character (\n) at the end. You can also use document.open() and document.close(). These don't actually write anything and they don't open or close a window, like window.open() and window.close(). document.open() opens the current document so that you can include several write() statements that will execute at the same time. After the write() statements you should include document.close(). This will clear the current document and display the content in the write() statements. BROWSER'S HISTORY One popular use of Javascript is to include back and forward buttons. You can use history.back() for a back button and history.forward() for a forward button but there is a better way. The back() and forward() methods do not work correctly in some browsers. You should use history.go() instead. You can use history.go(-1) for back and history.go(1) for a forward button. The go() method is more widely supported, so you should use it instead. You can include any number within the parentheses, negative for the number of pages to go back and positive for the number of pages to go forward (history.go(-5) is the equivalent of hitting back 5 times and history.go(5) is the equivalent of hitting forward 5 times). You must remember though that if the visitor does not have the number of items in his/her history folder that you use for your back or forward button they cannot go back or forward that many times.
THE location OBJECT You can also change and
receive the location of the page with Javascript. You can
even load two frames or windows at once GETTING INFORMATION ABOUT THE DOCUMENT You can get lots of
information about the document using Javascript. You can access
things such as the title, referrer, last modified date, location,
background color, etc. Here are a couple of things I commonly
use when scripting.
document.title - title of the document (defined by the <title> tag) document.referrer - the page the visitor came from document.lastModified - the date the page was last modified (sent from the server, so Javascript depends on server accuracy and support for this feature) history.go() - used for back and forward buttons, use history.go(-1) for back and history.go(1) for forward location.pathname - location of the window (the location in the address bar, ex. http://w3nation.com/) document.location - location of the document (the location of the page) The difference between the last two is that if you have frames on your page location.pathname will show the location of the frameset and document.location will show the location of the individual page. CREATING CUSTOM OBJECTS Now you're getting to
some of the more complicated parts of Javascript (you might
consider reading this section more than once). With a custom
object you start pretty much from the ground up. You create
the object, the properties, and the methods.
ADDING TO OBJECTS You can also add more
properties and methods to objects that have already been created
using the prototype keyword. One example is using the prototype
keyword with the string object to create headings. Part 7 - EventsEVENT HANDLERS - USING THE MOUSE Javascript can also
execute on events, when something happens to the browser.
All executions made by Javascript do not have to be made in
a certain sequence. Event handlers are used to tell the browser
what to do when a particular event occurs.
<a href="#" onMouseOver="alert('This is a test link.')">Test Link</a> This syntax would display an alert message when you move the mouse over. Test Link, that link would be the equivalent to the above syntax. As you can see when you move your mouse over the link you get an alert. This is your basic event. You can also use the following events. onClick="" - executes when the user clicks the mouse button onDblClick="" - executes when the user double clicks the mouse button onMouseOver="" - executes when the mouse is over the object onMouseOut="" - executes when the mouse goes off of the object onMouseDown="" - executes when the user presses the mouse button onMouseUp="" - executes when the user releases the mouse button One thing about using event handlers with links is that the event handler is executed before the page changes. This means you can keep the page from changing (remember though, this could confuse and/or annoy your visitor). If your onClick event handler returns false the page will not change. You can use a confirm to make sure the user wants to leave your site. <a href="#" onClick="return confirm('Are you sure you want to leave this site?')">Leave this site</a> If you click that link it will give you a confirm message and if you click OK the page will change but if you click Cancel the page will not change. This works because of the event handler receives a false value it does not execute the link. You could also use this in a more complicated script. As long as the event handler does not receive a false value it will execute the link. EVENT HANDLERS - USING THE KEYBOARD With Javascript 1.2 and
1.3 you can also respond to the events caused by the keyboard.
I use the following script to capture key commands. I will
explain it to you so that you can create your own, but you
are free to use the one given if you wish. (Note: The numbers
aren't needed, they are simply there to help you) |