In the Javascripts Free
Scripting Tutorial I will completely cover all of the capabilities
Javascript offers. Javascript is a scripting language that allows you
to make your website more interactive. While HTML provides the
structure and CSS provides the styling, Javascript allows you to add
functionality to your website that users visitors expect.
I provide a tutorial on How to Use CSS Here and you can Learn How to Write HTML W3C Here.
Introduction to the Scripting Tutorial
In this first article, I'm going to give you a brief overview on how
Javascript works. In those articles that follow I will teach by walking
you step-by-step through real working Javascript Scripts.I'm going to
assume you have read or watched the above HTML and CSS tutorials.
Anytime I refer to Javascript Code, I'm talking about a series of commands I am making to the browser.
You know now that HTML is a structuring language that provides
structure to a website by surrounding all of the content with
<Tags>. Javascript gives you the ability to manipulate those tags
even further than you can with CSS. Javascript attaches an event
handler to the HTML tags, and then performs an action when a specific
event occurs. For example:
- When a page loads, Javascript code is made aware of that if there is an event handler assigned
- If a person puts their mouse pointer on an image, Javascript code
knows if an event handler has been assigned to watch out for that action
- If a person clicks on the submit button in a form, javascript knows if an event handler has been assigned.
To put it simply an event handler is an alarm that alerts Javascript
code to do something if the alarm has been triggered by some action the
visitor performs. Now on to where to place your Javascript code.
Where do you Write your Javascript
Like CSS, you can either write the code directly into a web page, or
link to an external Javascript file, that contains the code. If you
want to embed the code in the HTML file create this tag <script
language="javascript" type="text/javascript"> in between your head
tags. After you are done writing your code end the script with the
closing script tag </script>.
The preferred way to use Javascript code, is to link to an external
file. The reason it is better to link to an out side file includes:
- It helps you avoid changing the code on multiple pages
- It keeps your HTML pages neat and clean
You link to an external Javascript page by typing <script
language="javascript" src="javacode.js"> between the head tags.
Please note that the javacode file ends with the extention .js, make
sure when you save your code in the future it has that same extention.
Before I finish this part of the article, I want you to be aware
that a small percentage of browsers don't support Javascript. So you
want to add <! - Hide Javascript code, before your code. So to be
safe your code would look like this if you embedded the Javascript:
<script language="javascript" type="text/javascript">
<! - Hide Javascript
... Your Javascript Code ...
// -> Stop Hiding Code
</script>
I'm starting to feel like Columbo, but "One More thing... " If you want
to alert people that your website is much better with a Javascript
browser, or Javascript enabled put the following in your HTML:
<noscript>
You must use a Javascript enabled browser to get the most from this
website. Please install a newer version of Firefox, Opera, Safari or
Internet Explorer, to get the most from the internet.
</noscript>
The Javascript Scripting Basics
I wrote above that, Javascript attaches event handlers to HTML code
and then performs certain actions when certain events occur. These web
page components are referred to as the Document Object Model (DOM).
This is very easy to understand after you have seen some examples, I
just wanted to mention it now so I didn't have to type Document Object
Model again.
Javascript code is made up from the following series of commands:
- Functions: Groupings of statements that you can
type once and then use over and over again. Ex. Let's say you need to
add a bunch of numbers together over and over in your program. It's
easiest to give that series of additions a name and then have that Function done for you each time you call that Function, than it is to type the code over and over again.
- Loops: You use looping statements to perform a
repetitive action over and over until some condition is met. Ex. Add
one to this number over and over again until it is equal to 10,000.
- Conditionals: Conditionals provide you with the
ability to do one thing is something is true and do another thing if it
is false. Ex. If your best friend buys you a gift on your birthday,
thank him and if not, punch him.
- Variables: Variables are locations that you define
you want to store information in. Ex. You store your receipts and
checks in a box named Taxes, so that you know where to find them come
tax day. Think of a variable as a labeled box you store stuff in.
- Pre-Built Functions & Operators: Javascript
includes many functions that will perform common actions for you. Also
it has all of the common operators such as +, -, *, =, etc.
- Comments: Javascript provides you with the ability
to leave notes or comments inside of your code. Here you would describe
what the code is doing. You can define that something is a comment by
starting the line with // and then everything that follows til the end
of the line will be ignored. Or, you could comment out multiple lines
by typing this /* ... .Code... */
Javascript Functions
Like I said above functions are, groupings of statements that you
can type once and then use over and over again. This is what a function
definition looks like:
function nameoffunction( parameter1, parameter2)
{
javascript code...
return value;
}
And here is a real function:
function addThese(numberOne, numberTwo)
{
var total = numberOne + numberTwo;
return total;
}
- This code gives the function the name "addThese".
- It defines that it accepts two numbers, that will be assigned the name numberOne and numberTwo.
- It creates a variable named total and gives it the value of the two variables added together
- It returns the value of the addition, back to the location that called for the function.
You would call for the above function like this: addition = addThese(firstNumber, secondNumber);
Or, you could embed the function like this: bigAddition = addThese(firstNumber, secondNumber) + 2;
That is all there is to know about creating and calling functions in
Javascript. If you don't think your totally getting it wait for the
examples ahead.
Javascript Looping
The For Loop
You use looping to perform an action over and over again. One of the
ways you can loop, is to use what is called a for loop. A for loop
continues performing actions until a condition is met. This is the
basic structure of a for loop:
for (initial expression; condition to be met; edit the value of expression)
{
... javascript code...
}
An example of a real for loop looks like this:
for (var i = 1; i < 100; i++)
{
document.writelin(i);
}
The above code performs the following actions:
- Create a variable i and assign it an initial value of 1
- Define that the code below will be performed over and over until i is no longer less than 100
- i++, is shorthand for add 1 to i. This action will be preformed
after the code below is run through. So, the first number printed will
be the number 1.
- The code document.writelin(i); prints the value of i on the browser
screen. document.writeln, is a prebuilt function for writing to the
browser screen and it is ended with a semicolon (;)
- The curly braces are used to define the code that needs to be performed over and over again.
The While Loop
A while loop can also be used for looping. It's basic structure is:
while (condition)
{
... code...
iterator
}
An example of a real while loop:
while ( i < 100)
{
document.writelin(i);
i++;
}
It performs the same action as the previous for loop.
The Do-While Loop
The Do-While loop is almost identical to the while loop except it
doesn't check if the condition has been met before executing the code
in curly braces first. It's basic structure is:
do {
... code...
}
while ( i < 100 )
An example of a real do-while loop:
var i = 1;
do{
document.writelin(i);
i++;
}
while( i < 100 )
This code performs the same exact actions as the previous for and while loop.
The For-In Loop
The final looping tool may be a little confusing. Everything in
Javascript is considered an object. Objects have variables and
functions that they can perform. Programming languages used to be
called procedural languages because they mainly performed an action and
then another over and over again. Then a new form of programming was
invented called object oriented programming. Through OOP, you instead
create a bunch of objects that interact with each other. I'll dive more
into this subject later, but I thought I should explain OOP before I
dive into the next loop.
You use the for-in loop for looping through all of the variables of
an object. If you have variables assigned to an object you created,
this loop cycles through them. Here is the basic structure of a for-in
loop:
for (var objectVariable in objectItself)
{
... code...
}
Here is a real example:
for (var objectVariable in objectItself)
{
infoOnObject = objectName + "." + objectVariable + " = " + objectItself[objectVariable];
document.writelin(infoOnObject);
}
If the previous code is confusing, skip it and we'll come back to it later. Otherwise, this is what it is doing:
- The for-in loop, loops through all of the variables of the object, which is named "objectItself"
- Each time it finds a new variable it assigns that variable to the variable objectVariable
- Then the name of the objects variable and the value of that variable are combined and stored in the variable infoOnObject
- Then the function document.writelin prints out the variable name and variable value, to the browser screen. Ex. "variable1 = 23″
We'll talk a lot more about objects later. Don't worry if you didn't totally grasp this one concept.
Javascript Variables
Variables are locations that you define you want to store
information in. You use the keyword var to tell the browser you want to
create a new place to store information and then assign that variable
with a value. Ex. var myEmail = "[email protected]";
You can change the value of a variable at anytime, just by assigning
it a new value with the equals sign. The name of your variable can
contain any letter of number and it is considered good form to start
the name with a lower case letter and then capitalize each word there
after. Ex. thisIsANiceName
Variables created inside of functions are only accessible inside of
the function in which they are declared. If you want to be able to
access a variable anywhere in your Javascript program make sure that
you declare it outside of a function. You should also never create two
variables with the same name.
Unlike most programming languages, Javascript is what they call
loosely typed. You see most languages require you to tell them what
types of information you will assign to a variable. Is it a small
number, a really big number, text, etc. Javascript doesn't care, except
for a few instances. You can assign a number to a variable name and
then text. Javascript will even convert text into a number and add it
to another number, if at all possible. Ex:
var numberOne = 5; // Creates a variable named numberOne and assigns the value of 5 to it
var textTwo ="10″; // Creates a variable named textTwo and assigns the text string "10″ to it
document.writelin(numberOne + textTwo); // Would print 15 to the screen
even though textTwo is technically text and not a number.
Variables that Must be Defined
Arrays
There are only two variable types that must be declared, the Array
and Date data types. An array is a variable that can store multiple
values. You create an array as such: var vehicles = new Array("car",
"truck", "van");
The values of this array variable can now be accessed by specifying
the number of the value stored in the array. The numbers are assigned
from zero on up. For example:
- The value of vehicles[0] is equal to car
- The value of vehicles[1] is equal to truck
- The value of vehicles[2] is equal to van
You can also add additional values to the array. For example to add
"bicycle" to the array, you would type: vehicles[3] = "bicycles";
Dates
You define a date variable in the following ways:
- var today = new Date(); // Will create a Date Variable and call the Date() function to assign the current time and date to it
- var myBirthDay = new Date(1974, 12, 21); // Creates a Date variable and assigns my birthday to it
Javascript Pre-Built Functions & Operators
There are many pre-built functions and operators available to you
with Javascript Scripting. To finish this article I'll go over a few of
the most common operators for you:
- + (Addition): Used to add numeric values or combine 2 strings of text
- - (Subtraction): Used to subtract values
- * (Multiply): Used to multiply values
- / (Divide): Used to divide values
- % (Modulus): Used to return the remainder of a division of two numbers. Ex. 15 % 7 = 1
- ++ (Increment): Shorthand way to add one to a value.
- - (Decrement): Shorthand way to subtract one from a value
You can also use a shorthand notation to add and then assign a value to a variable. Ex:
- x += y: Adds x and y, then stores that value in the variable x
- x -= y: Subtracts y from x, then stores that value in the variable x
In the looping section above we were performing comparisons. Here is a list of the ways you can compare information:
- x == y: Tests whether x equals y
- x < y: Tests whether x is less than y
- x > y: Tests whether x is less than y
- x <= y: Tests whether x is less than or equal to y
- x >= y: Tests whether x is greater than or equal to y
- x != y: Tests whether x is not equal to y
- x= (y < 5) ? 10 : 15 : Shorthand way to test and then assign a
value based on the test. This code tests if y<5, if the answer is
TRUE then x is assigned the value of 10, if not x is assigned the value
of 15
Finally, there are three operators that can be used to test further
on how different values compare. These operators are referred to as
logical operators and include the following:
- if ( x < y && a > b ): && is used here to
check if both comparisons are TRUE. If x < y is true AND a > b,
then this comparison returns the answer TRUE. If either is not TRUE it
returns the value FALSE.
- if ( x < y || a > b ): || is used to see if just one
comparison is TRUE. If one or the other or both comparisons are TRUE,
then TRUE is returned, if both are untrue then FALSE is returned.
- if (!x): This is the NOT operator. It is used to check if values are not equal to the variable it is being used on.
That's all Folks
Well that is it for now. In the next article I'll explain what
objects are and how they are used in Javascript. As well I'll go into
detail on how you use the Document Object Model (DOM) to jazz up your
web pages.
If you have questions or comments leave them below.
Till next time...
|