Free Javascript Scripting Tutorial Part2

In this article I’ll explain Javascript Scripting. If you haven’t read my previous article on Javascript Scripting you should read it first. It provides a brief overview on the capabilities of Javascript. Here is the location of the code you’ll be working with, to see what you’ll learn. Here I’ll run you through some Javascript code and explain the following:

General HTML Stuff

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />
<title>JavaScript Tutorial</title>

Here I’m telling the browser what version of HTML I’m working with. You do this to make sure your website looks the same on every device that supports internet browsing. I created a complete tutorial on HTML and if all of the information above is confusing read it first. Here is the HTML W3C tutorial.

<script type=”text/javascript”>

<!– Hide this from browsers that don’t understand Javascript

Embed & Hide Javascript from Browsers that Don’t Support it

You use the script tag above to tell the browser that everything that lies between the opening script tag and the closing script tag is Javascript code and should be processed as such. You don’t have to include the line: type=”text/javascript”, because browsers consider anything enclosed between <script> tags to be Javascript by default, but it is considered good form.

<!– is used to define a comment in HTML. A comment is completely ignored when reading HTML code. We are using that fact here to hide all of the Javascript code from browsers that don’t understand or don’t have Javascript enabled on their browser. You can write whatever you want after the symbols <!–.

function editNodeText(id, newText) {

How to create Functions

Here I’m creating a function. You create functions to avoid duplicating code over and over through out your program. With a function you define how to perform a series of actions and then just call it else where in the script when ever you need this code.

You define a new function, by typing the keyword function, followed by the name of the function you are creating. It is considered good form to start your function name with a lowercase letter and an uppercase letter for each word there after, but this is not a requirement of Javascript.

I then tell the browser that this function expects two variables will be past over to this function when it is called else where in the Javascript Script.

To finish off the beginning of this function you need a curly brace {. Everything between the opening and closing curly brace }, defines the body of the function.

var node = document.getElementById(id);
while (node.firstChild)
node.removeChild(node.firstChild);
node.appendChild(document.createTextNode(newText));
}

Creating Variables, The Document Object Model & Nodes

Here is probably the most complicated part of this whole script. To understand this code you have to understand what the Document Object Model (DOM) is. The DOM allows you to access all of the objects that lie in your HTML code. Every web page is considered to be a document object. To learn what an object is read my tutorial What is Object Oriented Programming.

So if the browser considers the whole web page to be a document object, how can we work with and edit the HTML by manipulating the document object? HTML documents contain text, images, links, CSS style tags, form elements, etc. These tags are referred to as nodes in the DOM. Javascript can be used to manipulate these HTML elements by referring to them by their defined HTML id name.

In the body of the HTML code below I create a span that contains text, with the following HTML code:

<span id=”ifSpanEx” onclick=”testingIfValue(1,4)”>Compare the values 1 and 4 using a If then Else statement. Click Here for Results</span>

This is a node referred to as ifSpanEx, because that is the id name I gave to it. This is like any other variable and can be given any name you want. In the code:

var node = document.getElementById(id);

  • I create a variable using the keyword var, you define all of your variables using the statement var.
  • The code says I want you to get me the element, being the span defined above, that has the id name defined
  • I pass that id name to the function getElementById()
  • I then assign a short cut that I will refer to as the variable named node.

In the following code:
while (node.firstChild)
node.removeChild(node.firstChild);
I am deleting the text that is currently in the span. I use a while loop, that is used to continually perform an action over and over again. In this case I am repeatedly asking whether there is text in the span. I then delete any text found in the span using the function removeChild(). Put plainly this code is looking for text in the span and if it finds any it is deleting it until the span is empty.
In the code:
node.appendChild(document.createTextNode(newText));
}
I’m saying I want to place new text in my now empty span. The function createTextNode() excepts a variable named newText, and creates a new node that will contain the text I give to it. You see, not only is a tag considered a node, but any block of text can also be considered a node in HTML.
I then use the function appendChild() to assign the newly created text node to the span.
I hope that was understandable? If not leave your questions in the comment section below. Take comfort in the fact that this is the most complicated part of this whole tutorial.

function testingIfValue( ifItem1, ifItem2 )
{

var valuePassed1 = ifItem1;
var valuePassed2 = ifItem2;
var valueToReturn = ” “;
var node;

Here I’m creating another function and defining all of the actions it will perform between curly braces {}. I then go on to define 4 new variables. valuePassed1 and valuePassed2, are assigned the values that were passed to the function. I then create a string variable and assign it a single space, which is between the quotes. Of course, I end all of these statements with the semicolon (;).

if (( valuePassed1 > valuePassed2 ) && ( valuePassed1 != valuePassed2 ))
{
valueToReturn = valuePassed1 + ” is greater than ” + valuePassed2;
} else {

if (( valuePassed2 > valuePassed1 ) && ( valuePassed1 != valuePassed2 ))
{
valueToReturn = valuePassed2 + ” is greater than ” + valuePassed1;
} else {

valueToReturn = valuePassed1 + ” is equal to ” + valuePassed2;
}
}

The If – then – Else Statements

Here I’m creating a conditional if than else set of statements. You use these statements to perform different actions based of of different conditions. In this case:

  • If valuePassed1 is greater than valuePassed2 AND valuePassed1 is NOT EQUAL TO valuePassed2, assign the right value to the string variable named valueToReturn. If that is not true perform the next conditional if check, otherwise jump out of the if statement block.
  • If valuePassed2 is greater than valuePassed1 AND valuePassed1 is NOT EQUAL TO valuePassed2, assign the right value to the string variable named valueToReturn. If that is not true perform the next conditional if check, otherwise jump out of the if statement block.
  • Finally if the above two if checks aren’t true, then perform the default statement, that will assign the given string to the variable valueToReturn.

All the Comparison Operators
There are 6 different ways you can compare data as I did above with the Greater Than (>) symbol.

  • >: Greater Than: Returns the value true if the value on the left is greater than the value on the right
  • <: Less Than: Returns the value true if the value on the left is less than the value on the right
  • >=: Greater Than or Equal to: Returns the value true if the value on the left is greater than or equal to the value on the right
  • <=: Less Than or Equal to: Returns the value true if the value on the left is less than or equal to the value on the right
  • ==: Equals: Returns the value true if the value on the left is equal to the value on the right
  • !=: Not Equal to: Returns the value true if the value on the left is not equal to the value on the right

All the Logical Operators
Logical Operators are often used in combination with comparison operators, when you have to perform more complicated comparisons. Above I was checking if the values were greater than each other AND not equal to each other. Here are the other Logical Operators:

  • &&: Logical AND: Returns true if both the value on the left and right equal true
  • ||: Logical OR: Returns true if either or both values on the left and right are true
  • !: Logical NOT: When it is placed in front of an operand it provides the opposite of the result of the comparison. Ex. if !(a>b), if a is greater than b, the result of this comparison would come back as false. I’ll provide examples on how to usefully use this tool later in the tutorial.

editNodeText(“ifSpanEx”,valueToReturn);

} // Closing curly brace for the function testingIfValue

Closing the Functions and Commenting

Here I’m calling the function editNodeText() and passing along some variables for it to work with. I already described what that function does.

Then I close my function with the closing curly brace }. The two forward slashes // tell the browser that this is a comment and that it can ignore everything that follows till the end of the line. You can also define a multi-line comment by starting it with /* and everything will be ignored until the following symbol is found */.

function testingSwitchValue(switchItem)
{
var valuePassed = switchItem;
var valueToReturn2 =””;

switch ( valuePassed ) {

case 0:
valueToReturn2 = “Zero was sent”;
break;

case 1:
valueToReturn2 = “One was sent”;
break;

case 2:
case 3:
valueToReturn2 = “Two or Three sent”;
break;

default: valueToReturn2 = “Number Bigger than Three was Sent”;
break;
}

editNodeText(“switchSpanEx”,valueToReturn2);

}// Closing curly brace for the function testingSwitchValue

The Switch Statement

The switch statement provides you with an easy way to analyze a single variable. It is tedious to repeatedly check a variable in a series of if statements. The switch statement accepts one vale and then checks if it equals a predefined set of values. case 0: asks if the value equals 0. If so it performs those statements that follow until it hits the break statement, which throws you out of the switch statement.

You can also perform the same action if the  variable equals multiple values, as I show above. If the variable equals 2 or 3, the same action is taken.

If the variable is not equal to any of the predefined values, the default statement is reached and those statements that follow the keyword default are executed.

Even though I don’t use it in the code there is another way to compare values and then perform which ever action you would like. It is called the Conditional Operator. Here is an example:

x > y ? y * 2 : x * 2

This statement checks if x is greater than y. If it is y is multiplied by 2. If not x is multiplied by 2.

function testingForLoop( firstValue, lastValue )
{

var startValue = firstValue;
var endValue = lastValue;
var valueToReturn = ” “;

for(var i = startValue; i <= endValue; i++) {
valueToReturn = valueToReturn + ” ” + i;
}

editNodeText(“forSpanEx”,valueToReturn);

} // Closing curly brace for function testingForLoop

The For Loop

Here I demonstrate how to use a For Loop in Javascript. You use a For Loop when you want to perform the same actions over and over until a specific condition is met. To create a for loop you:

  • Define the beginning of a for loop with the keyword for
  • After the bracket (, you define a value that will be iterating in some way to loop through the for loop
  • After the semi-colon, you define what condition will cause the looping to end. In this case, you will continue performing the actions blow until i <= the variable endValue.
  • After the semi-colon, you define how you are going to edit the iterator i. In this case I increment the variable i by one each time I have run through all of the actions in the for loop.
  • Then you define all of the actions you want repeated over and over, between the curly braces {}

You Can Edit Values with These Operators

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Modulo (%): Returns the remainder of a division. Hence, 5 % 2 would return 1
  • Increment (++): Shorthand way to increment a value by 1
  • Decrement (–): Shorthand way to decrease a value by 1
  • +=: Another shorthand way to add a value to a variable. Ex. sampVar += 2; would add two to the variable sampVar and then assign that new value to the variable sampVar
  • -=: Another shorthand way to subtract a value from a variable. Ex. sampVar -= 2; would subtract two from the variable sampVar and then assign that new value to the variable sampVar

function testingWhileLoop( firstValue, lastValue ) {

var startValue = firstValue;
var endValue = lastValue;
var valueToReturn = “”;

while ( endValue > startValue )
{
endValue–;
valueToReturn = valueToReturn + ” ” + endValue;
}

editNodeText(“whileSpanEx”,valueToReturn);

} // Closing curly brace for function testingWhileLoop

The While Loop

Here I’m using the While Loop, to repeatedly perform certain actions until a predefined condition is met. That condition in this case is repeat these actions until endValue is not greater than startValue. Just like the For Loop you must contain all of the actions between curly braces {}. You also must iterate values inside of that series of statements, instead of defining them at the top of the While Loop. In my case I decrement the value endValue with this statement: endValue –;

function testingDoWhileLoop( firstValue, lastValue ){

var startValue = firstValue;
var endValue = lastValue;
var valueToReturn = “”;

do {

valueToReturn = valueToReturn + ” ” + startValue;

startValue *= 2;

if( startValue > 40 ){
break;
}

}
while ( (startValue != endValue) || (startValue > endValue));

editNodeText(“doWhileSpanEx”,valueToReturn);

}// Closing curly brace for function testingDoWhileLoop

The Do While Loop

Here is the Do While Loop. You use a Do While Loop, when you want to guarantee the actions contained between the curly braces {} will be guaranteed to be executed at least once. They are guaranteed at least one execution because no conditions are checked until the end of the Do While statement.

I messed this Do While Loop on purpose to revisit the break statement. If I passed the function the values 2 and 20 you can see that the condition while ( (startValue != endValue) || (startValue > endValue)); would always return a value of true. This is referred to as an infinite loop and would cause my program to infinitely perform calculations until an error is thrown or the computer grinds to a hault.

Just so you understand even when startValue equals 20, causing (startValue != endValue) to return false the second condition (startValue > endValue) would still return true. Because I used the || logical operator only one or the other condition needs to be true to continue running the loop.

So why doesn’t this code cause an infinite loop? Because of the following code:

if( startValue > 40 ){
break;
}

This conditional test checks to see if the variable startValue is greater than 40. If it is the break statement, like it does with the switch conditional, kicks the user out of the loop. This is a nice way to avoid infinite loops, but simply writing good code also works.

There is another statement like the break statement, which I didn’t use in this code, but you will find useful. It is called the continue statement. Like the break statement, it kicks you out of the current series of statements that lie between the curly braces {}. The continue statement doesn’t kick you down and out of the loop, but instead just throws you back to the beginning of the loop and reiterates or simply just continues executing code after that loops opening curly brace {.

// –> Finish hiding the Javascript code
</script>

With the symbols // –> I finish hiding my Javascript from those browsers that don’t understand Javascript. Then I close the Javascript scripting area with the script closing tag </script>.

</head>

<body>

<h3>Javascript Tutorial</h3>

<span id=”ifSpanEx” onclick=”testingIfValue(1,4)”>Compare the values 1 and 4 using a If then Else statement. Click Here for Results</span><br /><br />

<span id=”switchSpanEx” onclick=”testingSwitchValue(2)”>Evaluate the number 2 with a Switch statement. Click Here for Results</span><br /><br />

<span id=”forSpanEx” onclick=”testingForLoop(2,20)”>List all the numbers from 2 to 20 with a For Loop. Click Here for Results</span><br /><br />

<span id=”whileSpanEx” onclick=”testingWhileLoop(2,20)”>List all the numbers from 20 to 2 with a While Loop. Click Here for Results</span><br /><br />

<span id=”doWhileSpanEx” onclick=”testingDoWhileLoop(2,20)”>Mess up a Do While Loop to show how the break statement works. Click Here for Results</span><br /><br />

Event Handlers & Changing Text on the Fly
Here I define a bunch of span’s. If you don’t understand this read my HTML W3C tutorial. I use the onclick attribute to trigger that the visitor has clicked on the text. When the text is clicked the function defined between quotes is called and executed. To see what happens when you interact with the script go to this page JSExample1.html.

</body>
</html>

These last few tags close the body and html document. That’s all I’m going to cover in this article on Javascript. If you have any questions leave them below. You learned a ton and in the next few articles you learn the rest and then you’ll be a Javascript Expert.

Till next time…

One Response to “Free Javascript Scripting Tutorial Part2”

  1. oren says:

    Hey thanks!

    I have a small problem…

    When I ruu the code as an HTML, everything looks as expected but when I click the , “Click Here for Results” – nothing happens….

    Any Idea?

    thanks again!

Trackbacks/Pingbacks

  1. Tweets that mention Free Javascript Scripting Tutorial, Javascripts Free | new think tank -- Topsy.com - [...] This post was mentioned on Twitter by Derek Banas. Derek Banas said: Published: Free Javascript Scripting Tutorial Part2 @…

Leave a Reply

Your email address will not be published.

Google+