Javascript

Learn

Our tutorials have been submitted by our own members and staff over the last four years. They cover a range of design packages and programming languages.

Tutorials are key part of learning new skills, so we not only recommend that you try some, we suggest you experiment with the framework that they give you, don't be scared to wander from the instructions.

Click the categories below to get started!

Contribute

Alternatively you can pass on your useful tips and advice to others, by creating your own.
Submit a Tutorial

Recommend to Others

If you like a tutorial, please use the "digg" button below it.

Introduction

Introduction.

In this tutorial I hope to show you what Javascript is, and what it can do for you and your visitors. Before I continue I must point out that i'm not an expert in javascript, the things you read from here are what i've read over the last year or so. Most of this introduction contains basic explanations and examples found across the internet and in books. Few things I would like to point out first before you continue on. When you come to viewing an example of code, don't just copy and paste it, type it out. From doing this you will learn to debug your code and fix any problems that arise, just a small thing that I suggest, but if you want to copy and paste, feel free to do so. :tongue:

What is Javascript and what can it do?

Javascript is a scripting language, which means that scripts included in the webpage are read by the web browser's javascript engine when the page is loaded. Javascript was created by Netscape which was originally called Livescript. There are loads of things you can do with Javascript to make your website more interesting for your visitors. From validating forms, interactive scripts, random images, popups, even make Javascript games.


The Script Block. In order to include Javascript in a web page, a script block must first be defined in the HTML code. The script block can be put anywhere within the HTML code, but usually it would go into the head part of the web page between the <head> tags. When the web page loads in the browser it reads the code, so placing it in the head of the web page ensures that the Javascript code is read before the HTML content, though you can place a script block inside the <body> tags. Example of a script block:

<script type="text/javascript">
<!--
//-->
</script>

Note: you might see some script blocks that contain the language attribute, this was used to specify the scripting language but I believe it has been removed in HTML 4.0. The actual code you make would go between <!-- and //-->. These are to hide the script from really old browsers that cannot interpret Javascript. You may also separate the Javascript code from the HTML code by putting the Javascript code into a Javascript file. A Javascript file is just a text document with the Javascript code in it but without any <script> tags or HTML tags. A Javascript file is saved with the extension ".js". To call the Javascript file to be loaded into the web page, you would use a script block like so:

<script type="text/javascript src="http://www.mydomain.com/myscript.js"></script>


Putting Comments in Scripts.

It's always a good idea to add comments to your scripts, why? well, come months later when you decide to make changes to your script it will be easier to find the block of code to change. I have a bad habit of not adding comments to my scripts but have found it very awkward making changes to a script. Here are 2 javascript examples: One line comment:

<script type="text/javascript">
<!--
//this is a one line comment
-->
</script>

Multi line comment:

<script type="text/javascript">
<!--
/* this is an example of a comment that can be added to multiple lines. */
//-->
</script>

For the one line comment you use // followed by your comment, this is fine for short comments, but when you need to add a much longer comment you can use example 2. For example 2 you start with /* which tells Javascript to ignore everything that follows until you reach */ to close the comment. Simple enough? :)


Hello World. For your first script we will look at the Javascript alert dialogue box. Take a look at the script below, then I will explain it.

<script type="text/javascript">
<!--
alert("Hello World");
//-->
</script>

For this small script we use the Javascript alert() function within the script block. When the web page is loaded the Javascript code causes the browser to open an alert box containing your message withing the quotes. So that's all it is, to have your message appear just place it within the alert function inside quotes. Note: it's good coding practise to end statements with the semi colon ;, although Javascript doesn't require it like some language (PHP) it's good to get in the habit of adding it.


Variables.

What's a variable? I hear you say.... Answer: A variable is a place in which you can store data. When you come to naming variables you must be aware of certain things. A variable can have any letter, digit and even the underscore _ may be used, but the variable may not begin with a digit. Example of valid variables: abcd my_variable var32123 To create a new variable, you use the Javascript "var" keyword. I'll show you with a small script.

<script type="text/javascript"> <!--
var my_message = "My First JavaScript Variable";
alert(my_message);
//-->
</script>

The text string is stored inside the variable called my_message. Then the variable name is called to the Javascript alert function that we talked about earlier, so when you run the script you will get an alert box displaying the string which is stored in the variable.

Scorpian's Guide to JavaScript [Part 1]

Are you a noob? Do you have no clue what JavaScript does? Do you want to learn? Fear not, for I am here to help! I'll guide you through all of the basics of JavaScript in these few, simple tutorials. :) First off, it's imperitive that you never get Java & JavaScript confused. Yes, they have similar names. However, that's the only similarity. They are two completely different languages that are meant to do completely different things. When NetScape made JavaScript, they decided to name it that since Java was already popular. It helped JavaScript grow pretty well. Now, just about every browser on the planet supports it.

First off, let's learn how to set-up a code tag. You can do this by two ways.

1.) You can embed your code with script tags.
2.) You can remotely host it. It doesn't matter which way you use, as you'll need to use script tags for both. So, let's learn how to set them up. A script tag is just an HTML element that let's the browser know that it needs to read everything in it as another type of script. It's mainly used for JavaScript.

The layout is pretty simple. <script type='text/javascript' src='myscript.js'></script>

I have color-coded this for you. The red parts are the script tags themselves. This is what tells the browser to stop reading HTML, and read a type of script.

The blue part tells the browser that the type of script it's going to be reading is JavaScript in a text format.

Now, the part is optional. If you remotely host your code, this is what tells the browser where it can find the script. It's used just like when you link to a stylesheet or image. Leave it out if you're not using a seperate script.

Now, let's learn the basics. Here's a code with some pretty simple elements of JavaScript that we'll learn:

<script type='text/javascript'>
// This line is a comment
/* This is all a comment */

var varName = "Variable Value";
</script>

Alright, the maroon parts are the opening & closing tags of our JavaScript segment. Everything you want to write in JavaScript goes between them.

The gray parts are comments. If you want to write something that the browser shouldn't pay attention to, you can comment it out, just like you comment in HTML. For a one-line comment, use //. For a multiple-line comment, start it with /*, and end it with */.

The bold navy part is what we use to define a variable. Simply start a line with "var", followed by a space, and put the variable name, shown in black.

Next, we'll add an equal sign, followed by the value of the variable. This is the part in blue, surrounded by quotes. Some things to note about variables is that you can combine different things into a variable using a + sign. For example: var

myName = "Scorpian"; var welcomeMessage = "Welcome, " + myName + ", to our site!";

This defines "Scorpian" as the value of myName. It then defines welcomeMessage as "Welcome, ", then whatever the value of myName is, and ", to our site!". This is very useful in simplifying scripts. You can also define multiple variables in one line if they all have the same value. For example:

var myMoney = myFunds = "3";

That shows that the variable myMoney will equal whatever the value of myFunds is, which we define as three. You may feel free to define as may variables as you want this way. Just separate them with equal signs. Well, that sums up the most basic of the basics for this tutorial.

Next tutorial, we'll learn how to use these variables. We'll also learn the infamous alert box, and how to use it. Stay tuned, folks. ;)

Javascript 101 (Variables, Arrays, Functions, If Statements + more)

You start with <script> and end with </script> every time. It is common to use cloaking from older browsers by adding <!-- to the beginning and //--> or just --> at the end

Comments

They are parts of a script that are not read by the Javascript console, they are for humans to read and are completely ignored by the browser. There are 2 ways of writing them: // This comment lasts for one line /* This comment last until I end it with this: */

Variables

Variables are used to hold data that can change each time a page loads. Variables are often used to make it so that you don't have to write something repeated times or to make it easier on people who don't understand how to edit every part. To declare a variable you simply write the var before it. Like this: var ok = "That's ok" To understand javascript you must know the difference between a string, a number and several other different values. The ones I use the most are strings, numbers, and boolean (I think) values. Strings are like sentences, however whenever you write a string you must have it some form of quotes, like this: "This is a string in double quotes" 'This is a string in single quotes' numbers are just written like they are, for example: 5 boolean values are true or false values and can ussualy be written in one of 2 ways (I'm pretty sure): 1. True or false 2. 1 (true) or 0 (false)

Some commands

if(){} for(){} alert() function blah(){} prompt() confirm() write() For if(){} you write the statement that you want to check to see if it's true, then in the brackets you write what you want it to do if it's true. An example:
var h = 5;
if(h == 5){
    document.write(h)
}
Note: I didn't use one = sign, I used two (==). One equal sign is saying what something equals, 2 is comparing. Javascript always starts counting from 0 and you need to remember that. It is a common error in alot of scripts.

Arrays

An array is something that holds multiple variables An example: var hey = new Array("Hey',"Hello","Hi","Wassup") or: var hey = new Array(); hey[0] = "Hey"; hey[1] = "Hello"; or: var hey = ["Hey',"Hello","Hi","Wassup"]. That's pretty much saying the 0th hey is "Hey" and the first hey is "Hello"

Functions

function sayIt(text){
    alert(text)
}
To call the function you would do this: sayIt("hello");. This would make an alert with "hello" in it, you could change hello to whatever you want. However, you wouldn't use functions for something stupid like that. Instead you'd do something like this: document.form.checkbox.onChange = "javascript: checkIt(this)" Then the function would look like this:

function sayIt(it){
    if(it.checked){
        document.form.checkbox2.checked = true;
    }
}

Alert, Confirm, Prompt

These are basic, preset functions.
Alert: alert("Hey"); \\Makes an alert that says: Hey
Confirm: confirm("Are you sure you wish to delete?"); Makes a confirm alert type thing. If it is chosen yes, then it will continue, otherwise it will go back.
Prompt: var size = prompt("What size would you like the image","#x#"); The "" set is the text, the second is the default in the prompt. Later you can call their answer by using the size variable.

Using an If

an if() statement is made when they are several possibilities, but you need a certain one. Or to check a value, and do something if it is, or isn't there. Here is one for making it that something only happens on one page instead of pages, because the main H&F applies to many pages:

if(location.href.indexOf(/action=profile&username)){
    document.write("heh");
}

The difference between write() and adding to a TD or something else

document.write("Can be used to"); write something where the script is located. It writes there, no need to obtain properties of a TD and insert it there. For adding something to something where a script cannot be placed should be used like this:

var TD = document.getElementsByTagName('td');
TD[5].innerHTML += 'This is the menu';

or adding to a form could go like this: document.postmodify.message.value += "This is the message area";

Javascript Basics (Variables, If-then statements, for loops)


Introduction to Javascript


You address javascript with the <script> tag.

//this is a comment

This is a comment. Comments are used to help guide someone through a script or code. The above is a one line comment. For comments that are more than one line use this /*Multiple line comment*/.

Variables - Variables are used to store data. This is very useful in javascript.

var myVariable = 5;

Let's take a look at this. var declares the variable. myVariable is the name of the newly declared variable. Next you will notice the = sign. This states that myVariable equals some value. Here, 5 is the value of my variable. The names of your variables can be anything (hello, myVariable, abc123, derfleurer, etc.). The same is true for their values. Another important thing to note is that variables are case sensitive.

var myVariable2 = "hello";

This is called a string. Keep in mind, the value of our previous variable (5) had no quotations around it. The difference is that the value of myVariable is identified as a number. If we had put quotations around it, it wouldn't have been identified by the browser as a number. To make it simple, strings are like sentences. How they're written is how they're displayed. Another thing about strings, never put a code such as prompt("",""); inside one. They cannot have quotations. If they did, then the value would be the code itself. If you wish to use a prompt, alert, etc. code as a value for a variable, DO NOT use quotations. Do as we did for myVariable.

You write variables just like text in JS. With one exception.

document.write("hello");

Here we see a basic code telling the browser to write hello in the page document. Now, as I said before, variables are used to store data. The exception to writing variables is that they will not have quotations around them. As you see below.

document.write(myVariable);

This will write the "value" of my variable onto the page. Get it? Now, onto alerts.

alert("hello");

This says to open an alert box when the page loads. In this case, the alert says hello. You can use variables here as well...heck, you'll use 'em almost everywhere (like I said, they're very useful). Next we'll take a look at prompts.

prompt("what's your name?","mike");

This calls a prompt. A prompt will have 2 parts. A question or request and an input value. The first set of quotations is the request. The second is the input value (either can be left blank). This particular one calls a prompt to the page that's asks you what your name is. The pre-set value is mike.


Arrays


Arrays are another very useful bit of javascript. They can be used to hold multiple values.

var myArray=newArray("my","what","a","lovely","day");

Ok, this declares a variable named myArray. The important part is newArray(). This states to create an array. Inside the parenthesis you will put your values.

How to write arrays

document.write(myArray[0]);

Ok, so you've declared your array...but how do you write it? Look at the above. We will be using the same variable as we did in our previous example. This states to write the the first value of our array. Javascript counts off from 0. So our first value will be #0. myArray[0] will write myArray's first value...which is my.

Now that you have all that down, let's cover if-then statements.


Javascript if-then statements



var question=prompt('2+2=','4');
var answer='4';
if (question==answer){
    alert("Correct!");
}

Alright, let's take a look at this. First off we declared some variables (question and answer). Then we created our if-then statement. if(question==answer){}. This statement says that if the value of question equals (==) the value of answer, execute the javascript in the curly brackets {}. What is the value of question? Well, it's not the prompt. If that were the case the value would be in quotations. The value of question is what the user inputs in the second set of quotations '4'. There are many ways to write if-then statements. You don't need to use strings or even variables. Look below, this is going to have the same outcome as our above statement.


var question=prompt('2+2=','4');
if(question == "4"){
    alert("Correct!");
}

The next won't be the same. You won't get the users input but the outcome will return true (like it would in the above codes if the user gave the correct answer).


if(2+2==4){
    alert("Correct!");
}

Now that you know how if-then statements work, it's time to write an if-then else.


var question=prompt("What's the password?","yokijo");
var answer="yokijo";
if(question==answer){
    alert('That's right!');
}else{
    alert('Better luck next time');
}

The above says that if the value of question equals the value of answer, execute the javascript in the {} brackets that follow. The new part here is else. In this case it says that if question does not equal answer, execute the javascript in the {} brackets that follow. So, if you gave the input yokijo you would recieve a message saying That's Right! and if you didn't you would recieve a message saying Better luck next time.


The Beauty of for loops


for loops are used to count through things in javascript. Study the example below and we'll get started.


for(var i=0; i<5; i++){
    document.write(i);
}

Above you will see our for loop for(){}. Inside we have declared a variable. I don't know why it must be declared inside the loop...I don't think there's as reason...it just does. The value of our variable is 0. The next two parts say that if the value of i is less than 5, increase i by one. We then wrote the variable in the brackets signaling to execute it only if the statement in the for loop is true.

I'm sure your wondering, "well is there a way to loop arrays?"


var myArray=newArray('1','2','3');
for(var n=0; n<myArray.length; n++){
    document.write(myArray[n]);
}

Yes. As you see above, the array is being looped. What's new here is .length and myArray[n]. The .length is attached to the array myArray.length. It is now addressed as thelength/number of values in the array. So, the above is just saying n=0, n is less than the length of values in myArray, increase n by 1. myArray[n] simply addresses the array looped with n.


Lesson Summary


So, we've covered the basics of

* how to declare javascript
* how to write comments
* how to write variables
* how to write strings
* how to write prompts & alerts

* how to write arrays
* how to write if-then statements
* how to write for loops

There is much more. But you may have to wait for my next tut.


Homework


I'd like you to try and write some of your own scripts and expirament a bit. Here are some examples for you. I'll break down the first one. Try and explain the others and if you think you got it p.m. me and i'll check it over.

<script>
var myPass=prompt("What's the password?","");
var theAnswer="yokijo";
if(myPass==theAnswer){
    alert("Correct!");
}else{
    alert("Wrong!");
}
</script>

Pretty obvious, right? First we declared some variables. myPass had a prompt value. theAnswer contains the value needed to make the if-then statement true. Neither of these variables do anything or have any meaning without if(){}. The if-then statement says that if the users input in myPass equals the value of theAnswer, execute the alert Correct! and if it doesn't, execute the alert Wrong!.

Your on your way. The next few examples are for you to play around with and break down. If there's something you don't understand, look back in the tutorial. If your still lost, p.m. me for support.

This first one is a bit tricky. I haven't gone over some of what you will see within it. So as I said above, you'll have to expirament. I will go into detail in the next tutorial.


<script>
var myPrompt=prompt("What's your name?","");
document.write("Hello " + myPrompt);
</script>


<script>
for(i=0;i<=9;i++){
    document.write(i);
}
</script>


<script>

var myPrompt=prompt("9x9=","81");
var myArray=new Array("That's right!","I'm disappointed in you.");
if(myPrompt=="81"){
    document.write(myArray[]);
}else{
    document.write(myArray[]);
}
</script>

cloneNode()

Explanation
Basically, cloneNode does exactly what it says. It clones an element and all of it's attributes, that can be modified without affecting the original node.

Syntax
node.cloneNode(true or false);

If the boolean value in the function is false, it does not clone any of the childNodes of the element. Yes, you guessed it. If the boolean value in the function is true, it also duplicates all of the childNodes of the element. This is usually the value used, as if it is false, it does not keep any of the text in the element either. However, it is sometimes usefull to have an empty node.

Example
Theoretical: In some cases, you are using elements to modify other elements. In doing so, the original element is changed, and you can not use it any more. So, a way around this is to clone the element, and use it. I was recently writing a script that put 2 columns in a table in order, but to do so, I had to change the innerHTML of each element with the elements in a sorted array. However, the elements in the array, were the same elements I was changing, so the elements in the array were being changed as the original ones were. This isn't what I wanted, so I cloned each row, and placed it in the array.

Real:
<html>
<body>
<p>Hello <b>there</b></p>
<p>Hello <i>ereht</i></p>
<script type="text/javascript">
<!--
// simple example
// lets put the bold there in the italic ereht
// there are better ways of doing this, but it is an example :P
var element = document.getElementsByTagName("p")[0].cloneNode(true); // why true?
document.getElementsByTagName("p")[1].lastChild.innerHTML = element.lastChild.innerHTML;
//-->
</script>
</body>
</html>

As you can see, cloneNode has its uses. Be carefull not to use it with something that has an id, as it will clone it. We don't want that, do we?

createDocumentFragment()

createDocumentFragment() is basically somewhere to store your newly created nodes before you append them to the document, then when you are ready to append all the nodes to the document, all you need to do is 1 append and they all get added.

Creating a fragment is extremely easy. Have a look at the example below to see how a fragment is created.

<script type="text/javascript">
<!--
var docFragment = document.createDocumentFragment();
//-->
</script>

Simple see? Nothing to it, you now have somewhere to store your new nodes. To add nodes to the fragment, all you need to do is append the childs to the fragment. See the example below to understand what I mean.

<script type="text/javascript">
<!--
var docFragment = document.createDocumentFragment();
var txt = document.createTextNode("my text node");
docFragment.appendChild(txt);
//-->
</script>

For the example above I created a new text node, and then used appendChild() to append the new text node to my fragment. So now my fragment holds 1 node. I could add more if I wished.

So what's the point in using it when you can just keep using appendChild()? To be honest I haven't found a big need to use it, but when I have, I use it when I do a lot of appending to the document. So instead of do 15 appendChild()'s at the end of my script, I can just do the 1, which would be to append the fragment, because throughout the script I will be appending them to the fragment, so when it comes to the end of my script all the new created nodes would now be stored in my fragment, just a matter of appending it to the document.

I'm sure there is more use for it then that, just that I haven't found a big need for it.

createElement()

For DOM, createElement is probably one of the handiest of all methods.

For this tutorial, we will create an image append it at the end of the document.

<script type="text/javascript">
<!--
var nImage = document.createElement("img");
//-->
</script>

Now that we have out created element, let's assign it the 'src' attribute.

<script type="text/javascript">
<!--
var nImage = document.createElement("img");
nImage.src = "http://www.solidsnakedesigns.com/images/smileys/smile.gif";
//-->
</script>

Now, for this tutorial I am just using the ' :smile: ' smilie as an example. This is optional, but it's something that I always like to do. Add a small portion give the newly create image no border.

<script type="text/javascript">
<!--
var nImage = document.createElement("img");
nImage.src = "http://www.solidsnakedesigns.com/images/smileys/smile.gif";
nImage.border = '0';
//-->
</script>

Now that our image is created and out attributes are set, let's append it to the document.

<script type="text/javascript">
<!--
var nImage = document.createElement("img");
nImage.src = "http://www.solidsnakedesigns.com/images/smileys/smile.gif";
nImage.border = '0';
document.body.appendChild(nImage);
//-->
</script>

There you have it :smile: . If you're using createElement to make a lot of objects for appending, then check out createDocumentFragment() by Peter.

CreateTextNode()

createTextNode() is pretty simple to use for creating text nodes. Check the example below.

<script type="text/javascript">
<!--
var myText = document.createTextNode("hello world");
//-->
</script>

As you can see we have a script with a variable called "myText" which is holding the text node we have just created. Creating text nodes with createTextNode will just be plain text, putting in tags to make it bold, italic etc, will not work, you will need to do more work with the text node to give it style. So, you have created your text node, but what do you do with it now? Well, now that you have created your text node, you need to append it to the document. Take a look at the script below.

<div id="mydiv"><div>
<script type="text/javascript">
<!--
var myText = document.createTextNode("hello world");
document.getElementById("mydiv").appendChild(myText);
//-->
</script>

Now, just above the script is a small bit of html, a div element, this will be used to place our new text node inside of it. Reason for the id="mydiv" is so that we can reference the object using getElementById. We then need to use appendChild() so that we can insert the new text node into our div element. appendChild() works by inserting the new node at the end, all you need to do is add a parameter, so in this case the parameter is "myText" since that is the new node we wish to add to the document. Once you get a good understanding of creating new text nodes and appending them to the document, you can then look into give the text some style. An example of what I mean is below.

<div id="mydiv"><div>
<script type="text/javascript">
<!--
var myText = document.createTextNode("hello world");
var font = document.createElement("font");
font.style.color = "red";
font.appendChild(myText);
document.getElementById("mydiv").appendChild(font);
//-->
</script>

Basically same as before, but this time we are adding the new text node to a font node we have created. var font = document.createElement("font"); The variable "font" now holds a new node we have just created, that new node being a font element. font.style.color = "red"; I wanted to make the new text red, so I set the font style color to red. font.appendChild(myText); All that is left is to add the text node to the font node, so the text node will be a child of the font node, we do this by using the appendChild() again, so now we would have something basically like....

<font style="color: red;">hello world</font>

....that now needs to be added to the document, so just like we did before, we appended the text node to the div, we will do the same but this time we will be appending the font node which already contains our new text node. document.getElementById("mydiv").appendChild(font); And finally, the last line to append the font node to the div container. Basically it, got any questions feel free to ask on the forum.

Functions

A function is a bit of code that can be used once or many times, and is made of statements to perform tasks. Each function you create in your script needs to have a unique name so that they can be called in your script. Below is a simple example of a function.

<script type="text/javascript">
<!--
function myFunction(){
    alert("hello world");
}
//-->
</script>

If you take a look at the script you will see that a function is made by using the "function" keyword before the function name "myFunction", which is then followed by parentheses and an open brace. The statements for your function go on the next line, then finally you close the function with a brace. Pretty simple isn't it?

So, you have made your function, but how do you call it? Easy, take the script above, when you call the function it will show an alert box displaying the message inside the quotes "hello world", now to call it, all you need to do is place myFunction() anywhere under it, placing it above the function will cause an error because the function hasn't loaded, a way to avoid that is to place functions inside your <head> tags and then you can call them anywhere in your document. take a look at the script below which shows you how I called the myFunction().

<script type="text/javascript">
<!--
function myFunction(){
    alert("hello world");
}
myFunction();
//-->
</script>

That's very basic way of calling the function, there are loads of other ways to go about calling them. A common way is to have the function run when the document has loaded, so to do this you could place the function inside your <body> tag using the event handler "onload", to understand what I mean take a look below. <body onload="myFunction()"> Now when the document has loaded you will then receive the alert box displaying the message. That's pretty basic, functions aren't limited to the example I have shown, we can also pass information back to the function, take a look at the example below.

<script type="text/javascript">
<!--
function myFunction(message){
    alert(message);
}
myFunction("hello world");
//-->
</script>

As you can see the function basically stays the same, only now the function "myFunction" has a parameter added "message", this is a function argument, so any information passed to the function is stored inside the "message" variable. To pass information to the function you just need to input some data. For this example we kept with "hello world", so if you look at myFunction("hello world"), all this is doing is passing "hello world" to the function which then gets alerted. So, what's so great about passing information back to a function? Many reasons why, and i'll show you an example.

<script type="text/javascript">
<!--
function myFunction(message){
    alert(message);
}
//-->
</script>

<input type="button" name="button1" onclick="myFunction('This is button 1');" />

<input type="button" name="button2" onclick="myFunction('This is button 2');" />

In the example above we have 2 buttons, each button is calling the same function but each button will display a different message when clicked on. We use the event handler "onclick", what this does is run the function when the button has been clicked on. So as you can see, with passing information back to a function like the example above you can have it perform a task, this saves having to write out the whole function again and again. Just a brief tutorial on functions, there is a lot more to be learnt about functions, but for now the basics will do.

getAttribute(), setAttribute(), and removeAttribute()

getAttribute(), setAttribute(), and removeAttribute()

getAttribute()

getAttribute() returns an attribute's value. It can be very useful and is really easy to learn. Here's the syntax: getAttribute(attribute) Here is an example for a document that had a table with a width of 300 and an id of "myTable":

<script type="text/javascript">
var theTablesWidth = document.getElementById("myTable").getAttribute("width");
</script>

The example above would make the variable theTablesWidth be equal to 300 because the table's width was 300.

setAttribute()

setAttribute() changes an attributes value by giving it a new one. It is extremely userful. Here's the syntax: setAttribute(attribute, theNewValue) Here is an example for a document that had a table with a width of 300 and an id of "myTable" (the same situation as before) >>

<script type="text/javascript">
document.getElementById("myTable").setAttribute("width","200");
</script>

The above example would change the table's width to 200. Here is another example for lets say I had a hyperlink with an id of "myLink" that linked to http://ssdesigns.proboards17.com:

<script type="text/javascript">
document.getElementById("myLink").setAttribute("href","http://www.solidsnakedesigns.com");
</script>

The above script would make the link that used to go to http://ssdesigns.proboards17.com now go to http://www.solidsnakedesigns.com.

removeAttribute()

removeAttribute() removes an attribute. It may be useful if you want something to change to the default setting. Here is an example for a document that had a table with a and an id of "myTable" (the same situation as before) >>

<script type="text/javascript">
document.getElementById("myTable").removeAttribute("width");
</script>

The above example would remove the table's width attribute, setting it to the default width.

Conclusion

Combining the powers of getAttribute(), setAttribute(,), removeAttribute() can give you pretty complex websites. Maybe you use getAttribute() to get a table's width and store it into a variable, and then use setAttribute() to increase the table's width by 100 pixels.

Hope you all enjoyed the tutorial and happy coding!

getElement & Forms With Javascript

getElement


One of the key elements in javascript codes is getting various elements from the HTML code. This tutorial will cover a few of the getElement types.

Example: What Does A getElement look like?

<div id="box"></div>

<script type="text/javascript">
document.getElementById('box').style.display="none";

</script>

In the above example, I've assigned the div that has the ID of box certain attributes. That's just a little thing to think of till the end of this tutorial... ;)

getElement Opening
A getElement handler is always opened by document., which means that it is getting the element from the current document. The document. is used in other JS methods, such as write().

getElement Closing
A getElement handler is always closed with brackets (A.K.A () ). You can either put the name of a variable into them or something enclosed in quotes. That something will depend on the type of the getElement.

getElements
Yes, there are also getElement types that are turned into plurals. Why? Because they repeat themselves or can repeat themselves throughout the document. getElement types that are turned into plurals will not be handled like single ones. These will either have to have a number assigned to them or be put into a loop. Below is an example of both with explanations.

<script type="text/javascript">
document.getElementsByTagName('td')[].style.display="none";
</script>

The only things I want you to notice in the above example are that the getElement is in plural and that there are square brackets after the closing brackets that include in them a number. Those square brackets with the number are the thing that assigns the number. The number of a certain element is determined according to the amount of times the same element repeats itself before. So, if you count and get to element no. 36, it'll actually be no. 35 in javascript.

<script type="text/javascript">
var td=document.getElementsByTagName('td');
for(t=0;t<td.length;t++){
    if(td[t].width="60%"){
        td[t].innerHTML+="Blah"
    }
}
</script>

Again, I only want you to notice a few things. They are listed below in order of appearance:
1. I inserted the plural getElement into a variable. Why? The name I assigned to the variable is much shorter, and as the getElement repeats itself a few times in the code, it is easier to insert a variable instead of the actual thing.
2. I'm using a for loop in this code. If you do not know what it is, I would suggest looking into derfleurer's tutorial. Back to the subject on hand, the loop will repeat as long as it is smaller than the length of the plural getElement. What is the length? The length is the number of times the element repeats itself. So basically, the loop will go through all the repetitions of the element that is referred to.
3. The if statement will determine what number of repetition to stop on. It'll actually turn the variable stated in the for loop to one or only a few numbers, meaning that you'll be in a level similar to the one in the first example. The difference is, you don't need to count. ;)
4. A reference to element with the set number/s in the if statement. It's pretty similar to the example in the beginning of the tutorial. The difference is that it's a plural getElement, thus you have the square brackets.

getElementById('ID')
Now to the first type of getElement I will be talking about: by id. If you are reading this tutorial, you probably have some basic knowledge in HTML, meaning that you know that various tags can have ids assigned to them. This type of getElement will search for the assigned ID (see the red part in the title), and will then use what it located to set various attributes for it. getElement attributes will be covered later on in this tutorial. Note that getElement by id will be the only non-plural getElement I will be referring to in this tutorial. The reason for it not to be plural is that you can only assign an id to one element at a time.

Side Note: The getElement by id is frequently used to hide things (see attributes section).

getElementsByName('NAME')
The next type of getElement I will be talking about is a plural one: by name. Names are usually assigned to form elements, so you will not be using this type of getElement much (find out why in the forms section). Remember: when using this type of getElement (plural), you must do what the plural section says.

getElementsByTagName('TAG')
The last type of getElement is the most used and most complicated: by tag name. This type of getElement can be used to locate any type of tag in your HTML document, from a simple b tag (bold) to an option tag (part of a drop-down). That can probably answer the question that you were asking yourselves when I said that this is the most used getElement, which was: why? Back to the point, you can replace the red TAG in the title with any tag name that exists. Remember: when using this type of getElement (plural), you must do what the plural section says.

getElement Attributes
getElement attributes are added in the following way:
getElementType.Attribute.Sub-Attribute (if any)="VALUE"

Note: The brown parts are attributes written in their case sensitive form.

Useful Resource: Microsoft's Reference Properties (Attributes) Library

Attribute:style - Below are Sub-Attributes and their Description

display:The most common values are inline, block and none. The block will add spaces on the top and bottom of the element, such as happens with the paragraph tag. The inline will do the exact opposite. The none will make everything inside the element invisible, and is mostly used with divs.

backgroundColor:This will assign a background color to the element. The value is set to a hex.

color:This will assign a text color to the element. The value is set to a hex.

To Make Long Things Short:Style is actually a "css in HTML" tag. Any css attribute can be used in it. The way css attributes are "translated" to JS can be found on the website of Microsoft.

Attribute:parentNode - This would be best explained with an example. <table><tr><td></td><td></td></tr></table> Look at the td tags. They are surrounded by the opening and closing tags of the tr. So the tr is "hugging them". Thus, it is the parentNode. Along the same lines, the table is the parentNode of the tr. Basically, the tags that wrap certain tags are their parentNode. Can you guess what the childNode is?

What To Do With parentNode? The parentNode is actually an additional part of the getElement. Consequently, it can have attributes, just like a regular getElement. That means that you can have the parentNode handler appear multiple times: getElementType.parentNode.parentNode.parentNode.attribute.and so forth.

Are There childNodes Too? Yes, childNodes are the exact opposite of parentNodes. Using my example, the tr is the childNode of the table and the td is the childNode of the tr. If you have noticed, the brown colored text in my question is a plural, meaning that the childNodes attribute needs to be in a loop. Let's see an example of how it's implemented.

<script type="text/javascript">
myTD=document.getElementsByTagName('td')[]

childs=myTD.childNodes;
for(t=0;t<childs.length;t++){
    if(childs[t].width=="66%"){
        alert('Width Match!');
    }
}
</script>

In this example, you might notice that I first got the TD element and assigned it a number. Then, I assigned that getElement a childNodes attribute. Afterward, I looped through the childNodes to find the one that I'm looking for. Like I explained above, parentNode (and thus also childNodes) is part of the getElement, so all getElement rules apply on it, including finding the needed one with a loop or assigning a number.

Attribute:className - There's no need to elaborate much about this attribute. The className attribute is quite obvious: it is used to assign a certain class to an element.

Attribute:width - Again, there's no need to elaborate much about this attribute. What it does is pretty obvious: assign a width to the referred to element.

Attribute:innerHTML - This attribute is used to make various actions with the HTML or text that are inside the referred to element. Below are Sub-Attributes and their Description.

replace:Used to replace parts of the contents of the referred to element. The way this attribute is used differs from the standard.

<script type="text/javascript">
var bold=document.getElementsByTagName('b')[];
bold.innerHTML=bold.innerHTML.replace('Dogs','Cats');
</script>

First, notice that I wrote that the contents of the element equal the replacement. Second, I would like you to notice the replace attribute has brackets next to it, with 2 words in quotes and a comma between. The left part is what the code looks for and the right part is what it will be replaced with. All the rules of document.write() apply on the contents of the quotes (including variable insertion).

Wait, I Think I Know What's Going On Here!

If you're thinking that all HTML attributes can be referred to (according to the above explanations), you are almost right. There are two HTML attributes that I know of that cannot be referred to when using the getElement tag: name (see why in the forms section), and id. There is a small problem that can easily be fixed with referring to HTML attributes: how do you know what the javascript case sensitive form of it is? I'd suggest using Microsoft's "library" which has all of the attributes in it with their HTML form and JS translation.

Attribute:nodeName
This will return the tag name of the element you are referring to. This attribute is only used either in an if statements to check the nodeName or to return the nodeName (with document.write for example), it cannot be set or reset.

Get An Element Inside An Element
Many elements have other elements inside them. For example a td sometimes has a font tag or a b tag in it. You can get that element using the childNodes attribute, or you can follow the below example.

<script type="text/javascript">
document.getElementsByTagName('td')[];

td.getElementsByTagName('b')[].innerHTML="Blah";
</script>

I would like you to notice the row below the variable. You can see that I took the getElement and assigned it another getElement as an attribute. The same rules of the regular getElement apply on a getElement inside a getElement.

To End This: How Do I Write Each of the getElement Types?
By Name: document.getElementsByName('NAME-OF-ELEMENT')
By ID: document.getElementById('ID-OF-ELEMENT')

By Tag Name: document.getElementsByTagName('TAG-NAME-OF-ELEMENT')


Forms & Javascript


The reactions between forms and JS are based on one of the getElement types: by name. You probably remember that I said you will not be using the byName type much because names are usually assigned to form elements, and I will now tell you that what I said wasn't accurate. Why? Look at the below code and try to find the answer by yourself.

<script type="text/javascript">
document.postForm.message.value=document.postForm.message.value.replace('I am','you are')';
</script>

Doesn't that look awfully familiar? There's a document. at the beggining and a replace attribute. So, what is that actually? The above is a referral to a form and one of it's elements. Let's translate that to a getElement.

<script.type="text/javascript">
for(z=0;z<document.getElementsByName('postForm');z++){
    for(x=0;x<document.getElementsByName('postForm')[].getElementsByName('message');x++){
document.getElementsByName('postForm')[].getElementsByName('message')[].value=document.getElementsByName('postForm')[].getElementsByName('message')[].value.replace('I am','you are');
    }
}
</script>

Both codes would actually do the same thing, but the first one is quite a few lines shorter. My point is, the first one is actually a getElement, but in a shortened form without loops or number assignments. In order of appearence: the postForm is the name of the form that we are referring to and the message is one of the fields of that form. That's the way we write things when we refer to various form fields in javascript. Forms have only one attribute that I can think of which does not appear in the actual HTML code which is: submit. If you make a button and make it's onclick equal to: document.postForm.submit(), the form named postForm will be submitted when the button is clicked.


Conclusion


I hope my explanations were clear enough and that I covered all the subjects that should be covered. Fell free to PM me if you want me to elaborate on a certain subject, improve my explantions, or add something new to this tutorial that seems missing to you.

~The Dog Monster

hasChildNodes()

This should be a very quick tutorial explaining how to use "hasChildNodes()".

When used, hasChildNodes() will return true or false if the node has any child nodes. A child node could be anything from a bold element to a table, check the example below to show how it works.

<div id="parent"> </div>
<script type="text/javascript">
<!--
var divObj = document.getElementById("parent");
if(divObj.hasChildNodes()){
    alert("Node has child nodes");
} else {
    alert("Node has no child nodes");
}
//-->
</script>

Pay attention to the div element above the script, if you notice, there are no elements inside of it. In the script we start of by storing the object in a variable called "divObj" by grabbing the div id using getElementById. Now that we have the object we wish to test on, we then create an if else statement to find out if the node (the div object) has got any child nodes.

Because the div has no child nodes, when we come to execute our script we will get an alert box with the message "Node has no child nodes", this is because the div element has no child nodes. Check the other example below that is the same script except the div element has got child nodes this time.

<div id="parent">
<b>text</b>
<i>more text</i>
</div>
<script type="text/javascript">
<!--
var divObj = document.getElementById("parent");
if(divObj.hasChildNodes()){
    alert("Node has child nodes");
} else {
    alert("Node has no child nodes");
}
//-->
</script>

Now, this time the div element has got 2 nodes, a bold element and an italic element, this time when we execute out script the statement will return true and we will get the alert box with the message "Node has child nodes".

insertRow() & insertCell()

The insertRow() and insertCell() functions are used to add rows (tr's) and cells (td's) into a table which is already on the page. Here's a small table code on which we will be using insertRow() and insertCell().

<table id="table"> <tbody id="tbody"> <tr> <td> Cell Info1 </td> </tr> <tr> <td> Cell Info2 </td> </tr> </tbody> </table>

We have 1 table, 1 tbody, 2 rows and 2 cells in this example. You don't need to add a tbody tag when creating a table in HTML, but when you use functions such as insertRow() where you will be adding rows, you have to add them to the tbody and not the table. Because it is the tbody that actually holds the rows and the cells, not the table. As you can see, I have added a ID to the tbody tag, if there is no ID on the table or tbody tag you can use the "getElementsByTagName" function. Let's add a row and a cell to the end of the tbody.

<script type="text/javascript">
var tBody = document.getElementById('tbody');
var iRow = tBody.insertRow(2);
var iCell = iRow.insertCell(0);
iCell.innerHTML = 'Cell Info3';
</script>

Now let's break the code down :)

var tBody = document.getElementById('tbody');

Gets the tbody tag with the "getElementById" function and assigns it to the variable "tBody".

var iRow = tBody.insertRow(2);
var iCell = iRow.insertCell(0);

The argument you pass on in the insertRow function is a integer representing the location of where you want to add the row. Because we want to add a third row, remember we start counting at 0 with javascript, we add a 2 as the argument. If you, instead of the 2, inserted a 3 as the argument, the code would return a error. Because you can't add a fourth row if there is not yet a third one ;). So the newly added row is assigned to the variable "iRow". We then add a cell to that row with the insertCell() function. The arguments work the same here as with insertRow(), only this time they're for cells :P.

If you are uncertain how many rows there are a the tbody and still want to add a row at the end of the table. You can use ".rows.length" which you add after a grabbing a tbody: "document.getElementById('tbody').rows.length" This will return a integer value, but this method does not start counting at zero, so with "document.getElementById('tbody').rows.length" it would return 2 which we can also put in the insertRow() function as shown in the example (where we used 2), to add a row to the end of the table. Here's how we can use this method:

<script type="text/javascript">
var tBody = document.getElementById('tbody');
var iRow = tBody.insertRow(tBody.rows.length);
var iCell = iRow.insertCell(0);
iCell.innerHTML = 'Cell Info3';
</script>

See how I added "tBody.rows.length" as the argument of the insertRow() function? If you grabbed a table instead of the tbody, and you want to use these 2 functions, you can use ".firstChild". So it would look something like this:

<script type="text/javascript">
var Table = document.getElementById('table');
Table.firstChild.insertRow(2);
</script>

Even if you can't see a tbody tag, it is always there, even if you don't add the tag itself. So that's basicly how these 2 functions work. Have fun with them ^_^

isNaN()

isNaN() is used to check if the value passed as the parameter is not a numeric value. NaN means not a number. So, isNan means is not a number.

An example where this could be used is in a page submission script. Here is a simple example of it being used in an if statement.

<script>
var let = "letters"; // this is not a number
//checks to see if it isn’t
if(isNaN(let)){
    alert("Please enter a number"); // if it isn’t it displays Please enter a number
} else {
    alert("You entered a number"); //if it is it displays You entered a number
}
</script>

In the first example this can be used to alert the user to hit back in there browser and enter a number if the code is changed to do so. You now know how to use isNaN. I hope you can find some uses for it.

Javascript Objects

Introduction

Welcome to the javascript objects. By now you should already have a firm grasp over javascript basics. Which you might be wondering what the heck they are. An object is the to me the equivalent of an OOP class. I'm sure you've heard of and used several objects before, most likely without even realizing it. Perhaps they will ring a bell: String Array Date Number

I'll go over how to modify the existing ones and how to create your own.

A bit more about the terms

Object - A class/constructor
Instance - A certain instance of an object
Property - A variable held by an instance/object
Method - A function held by an instance/object
this - It refers the instance inside of methods and properties.

Prototype

Prototype is the key to being able to edit existing objects such as string or array. I'll start off with an example of a method:

String.prototype.tell = function() {
    alert(this);
}

Now, you first might be wondering what this does and how to use it. Which brings me to another example:

var example = 'This is an instance of a string.';
example.tell();

The output of example.tell() would be "This is an instance of a string." It simply alerts the value of the string. You might also question as to why it is example.tell() instead of String.tell(). The simple answer is this: When using objects you will most likely have several instances, since you will most likely want functions that work with the value of the instance. One more example just to push you in the right direction:

Number.prototype.dbl = function(){
    return this * 2;
}
var x = 5;
alert(x.dbl()); //Will alert 10

Creating your own objects

Like last time I'm going to start with an example, it's fairly simple and you should be able to get the general idea of how it works:

function Person(first,last,age){
    this.first = first;
    //Properties
    this.last = last;
    this.age = age;
    this.greet = function(){//Method
        alert('Hello my name is '+this.first+' '+this.last+'.');
    }
}
var john = new Person('John','Doe',35);
john.greet();
alert(john.age);
//Alerts 35
var jill = new Person('Jill','Doe',64);
jill.greet();
alert(jill.age);
//Alerts 64

There it is, a very simple custom object. The Person object has a total of 5 properties which are first, last, age, prototype, and constructor. Prototype and constructor are default properties included in every object. It has only has the one method of greet. Custom objects are used to make things go faster. Imagine if you had to do something like this for each person instead of using the Person object when you have 500 people:

var johnFirst = 'John';
var johnLast = 'Doe';
var johnAge = 35;
function johnGreet() {
    alert('Hello my name is '+johnFirst+' '+johnLast+'.');
}

Summary Overall javascript objects aren't all that touch. It just takes a bit of time to read and experiment with. I challenge everyone who reads this to modify an existing object and to create their own object that has nothing to do with my Person object.

Looping Through TD Tags on Proboards

This tutorial will teach you how to target cells on Proboards forums, and will help on other forums and websites as well. First, let me put up a small code.

<script type = "text/javascript"> 
var td = document.getElementsByTagName('TD'); 
for(t=0;t<td.length;t++){ 
    if(td[t].width == "1%" && td[t].align == "center" && td[t].className == "titlebg" && td[t].innerHTML.match(/Topics/i)){ 
        td[t-1].innerHTML="FORUM NAME HERE";
    }
} 
</script>

Let's go through this code, line by line. First we start the code with <script type = "text/javascript"> obviously. Next line: var td = document.getElementsByTagName('TD'); sets up a Variable named "td" and assigns it to an element 'TD' which means a table cell. Basically now, evertime we bring up 'td' it will refer to a table cell. The next line for(t=0;t<td.length;t++){ first makes a variable, "t" then it gives it a value of 0. Then it says if it's lower than the value of "td" keep increasing it.

Just to make it easier, it's going to loop through all the table cells on the page. note the "{" this means anything { between } will happen IF for(t=0;t<td.length;t++) is done, which it automatically will be. But no need to worry about that. Next line: if(td[t].width == "1%" && td[t].align == "center" && td[t].className == "titlebg" && td[t].innerHTML.match(/Topics/i)){ This is describing what table cell we're trying to grab. In this case it's the Title Bar of a proboards forum. First, it says it's width is 1% then it says it's aligned to teh center, then it says it's class is titlebg, then it says the name is topics. Then the next line says td[t-1].innerHTML="FORUM NAME HERE"

Basically, since in the previous line we described what the variable "td" looks like, here we are saying, replace the table cell right before the cell 'td' is assigned to, and replace it with "FORUM NAME HERE". So, it says td[t-1], that means the variable td meaning the cell, and the variable t, meaning the whole description above. It's a little hard to understand, but still good for makin simple codes. Really easy, and when making Proboards Hacks, EXTREMELY usefull. Hope this helped. If you have any questions, please PM Me. Regards Nemo™

Object Inheritance

Introduction:

By now you should have read my tutorial on javascript objects and be able to create and manipulate objects. This is not that complicated if you already understand javascript objects and should be very easy to learn.

The Reasoning:

As objects shorten code, so does inheritance. Inheritance allows multiple objects to share properties/methods of a parent object. In a way javascript objects can have multiple parents, but not in the traditional sense. That is they do not officially have 2 or more parents, but they inherit from 2 or more objects.

Let Us Begin:

Making javascript objects have inheritance is really just a few lines that doesn't take long. Let us start off with our person object:

function Person(name,age) {
    this.name = name;
    this.age = age;
}

Now, what if we have two types of people that still need to have the properties of the person object? We could do the slow way and define those properties in each object or we could use inheritance. Here is another example assuming the person object is in existence:

function Student(name,age,grade,gpa) {
    this.grade = grade;
    this.gpa = gpa;
    this.parent = Person;
    this.parent(name,age);
}
function Employee(name,age,job) {
    this.job = job;
    this.parent = Person;
    this.parent(name,age);
}

That is the way you would do it with inheritance. With so few properties and no methods, it's not that big of a deal, and is in fact more lines just because this example is not that practical. However, with more properties and methods using inheritances the best option.

Multiple Inheritance:

As was said before, objects can have multiple parents through 1 of 2 ways. They can have the equivalent of grandparents by only inheriting one object itself, but since the parent object also inherits the properties/methods of both will be assigned to the grandchild object. The other method is to have multiple parents declared in the object. All you really do is the same method as above, except 2 or more separate times.

Traditional Inheritance:

Multiple inheritance is not technically supported because objects can only have 1 true parent, while they can inherit properties/methods from multiple objects. The reason I use multiple inheritance is because it is a generally close term to what the method of giving an object properties and methods from multiple object. The way to define a traditional parent is like so:

Student.prototype = new Person;

To be honest I have found no use for this as all my objects have arguments.

Summary:

Inheritance can be useful when you have a bunch of properties and methods that need to be shared from various objects. I hope you learned something from this and can find a use for it.

parentNode

parentNode is used to get the most outer node, think of parentNodes as containers, in the container you have child nodes, to see what I mean, take a look at the example below.

<div id="parent">
<b id="child">My text</b>
</div>

With the little snippet of HTML above, you have the parent node being a div container, in that container you have "child", that child being a bold element. If you were to grab the bold element by the id (getElementById()) and ask what its parent node is, the information sent back to you would be a div. Check the script below which gives you an example of how to do this.

<div id="parent">
<b id="child">My text</b>
</div>
<script type="text/javascript">
<!--
alert(document.getElementById("child").parentNode.nodeName);
//-->
</script>

With that script above we are telling the script to tell us what the node name is of the parent. So when we run the script, what happens is that we will get an alert box with the name of the parent element, which will be "div", if we didn't use nodeName after parentNode, we wouldn't be able to tell what the element is, all you would get is "[object]". With parentNode you aren't just limited to finding 1 parent,

child nodes can also be parents, take a look at the example below.

<div id="parent">
<div id="childparent">
<b id="child">My text</b>
</div>
</div>

With the above HTML we have 2 parents and 2 childs. The first div "parent" is a parent of the second div that is nested inside, so the second div is a child of "parent". Inside "childparent" we have the bold element "child", this is now a child of "childparent". So how do we access the childs parent parent element? Simple, check the script below.

<div id="parent">
<div id="childparent">
<b id="child">My text</b>
</div>
</div>
<script type="text/javascript">
<!--
alert(document.getElementById("child").parentNode.parentNode.nodeName);
//-->
</script>

Notice the 2 parentNode's? "parentNode.parentNode". The first parentNode is the div with the id "childparent", because we want to get the most outer parent element, we need to go out even further, so by adding another parentNode we reach the div with the id "parent".

With parentNode you aren't limited to just finding an elements nodeName, you can do more then that, for example, you could grab the parent node which contains the bold element, and then append a new node onto the end. Internet Explorer comes with its own version called parentElement, but for cross browser scripts I suggest you keep with parentNode.

Recursion

What is Recursion?

Recursion is an alternate method of performing something instead of iteratively. Iteration is the standard method of looping with something like while, or for, I'm sure that all of you know the drill. What you do with recursion is have a function call itself with a modified argument.

So How Does It Work?

One of the more common ways to demonstrate that is with a factorial, which is exactly what I'm going to do. As you know, a factorial is a number times all the whole numbers between it and 0. Lets go over the iterative method:

function factorial(x) {
    var work = x;
    while(x > 1) // Note that this is only this way because
    { // 1 * x = x, so there is no need to multiply by it
        work *= (--x);
    }
    return work;
}

As you can tell, this is probably the standard, normal way of doing it. But we can use recursion to make this code better:

function factorial(x) {
    if(x > 2) return x * factorial(x-1);
    return 1;
}

You see how a function can use itself to further perform its own duties? Its quite a useful method, and works rather well. From this you may be thinking that this is only useful for math and things like that, but once again this can be used for anything.

A DOM Example

Recursion can be used to perform the task of finding the exact pixel location of an object on the screen. Here is the code:

function getPosX(elem) {
    if(elem) return elem.offsetLeft + getPosX(elem.offsetParent);
    return 0;
}
function getPosY(elem) {
    if(elem) return elem.offsetTop + getPosX(elem.offsetParent);
    return 0;
}

Regular Expressions

Introduction

Regexp, or Regular Expressions are used to grab information based upon characters. It is much like split except easier in some ways are more complicated in others. It is made to only accept the kind of data you allow it to. It can be used for email verification and many other things. The cheatsheat below tells what each character does.

Basic Syntax

/regexp here/ The first slash is the beginning and the last slash is the end. You can add 2 letters, known as modifiers, after the last slash if you want. What they are and do: i-matches any case g-global search, this mean it doesn't stop after one. However, several times you must escape something. In the cheatsheat you may notice that the question mark does something. To get the litteral question mark you would do: ? A slash escapes any character's special value (besides those including a slash, like w). If you have another forward slash: / is the proper syntax. Or for a back slash: .

New RegExp

This is the syntax to make a variable regular expression: var regname = new RegExp(\"regular expression\", \"modifiers\"); The modifiers are the letters listed above. You can put either i, g, or gi.

Matches

You can select matches from parenthesis to obtain certain values. Lets say you have this somewhere on the page: A: 56 You'd then use this regexp to match it: /A: (n)/ Then you could output/use the value: document.write(RegExp.$1);

Greedy | Non-Greedy

This is a very commonly used idea. If it is greedy it will take as much as it can with still matching, where as non-greedy would take as little as it could. A common example might be in UBBC/html tags. If you want to match anything lets say the image url from an UBBC tag, and image UBBC tag.

The post/comment:

<img src=“http://blah.com/asdf.gif /> asdf <img src=“http://blah.com/jkl.gif />

Greedy would match:

http://blah.com/asdf.gif" /> asdf <img src=“http://blah.com/jkl.gif

Non-Greedy would match:

http://blah.com/asdf.gif

So how do you set the difference between greedy and non-greedy?

Well when you use a plus or * you just leave it to make it greedy and you add a ? after to make it non-greedy. So non-greedy would be: +? or *?.

Greedily match paragraph tags:

/(<p>|<P>)(.+)(</p>)/i

Non-greedily match:

/(<p>|<P>)(.+?)(</p>)/i

One last example

/^[w-.]+@[A-Z0-9-.]+$/i I'm just going to quickly break this down. / - beginning of regex ^ - starting at the begining of the string [w-.] - match a period, a dash and any letters, numbers, and underscoreds + - 1 or more of the previous @ - the at sign [A-Z0-9-.] - any letter, number, dash, or period. + - 1 or more of the previous $ - end of string /i - end of regex without matching case. If you can't already tell, this little regular expression checks for valid emails.

Regexp Cheatsheat

Code/Char - Definition/Match
^ - Start of string
$ - End of string
* - zero or more times
+ - one or more times
? - zero or one time
. - any character except newline
b - word boundary
B - non-word boundary
d - a digit
D - anything besides a digit
f - form feed
n - new line
r - carriage return
s - any spacing character
S - anything besides a space
t - tab
v - vertical tab
w - any letter, number or underscore
W - anything besides above
[abcde] - (part of) a string that matches any of those characters
[^abcde] - (part of) a string that matches anything but those characters
[a-e] - (part of) a string that matches the range of characters
{x} - exactly x occurrences of the previous character
{x,y} - x to y occurences of the previous character
() - a grouping
x|y - x or y

Switch()

The switch statement works like the if else statements but is more efficient when you need to test a the value of a variable. Take a look at both codes below, the first one uses the if else way, but the second one uses the switch way.

Example 1 - if else:

<script type="text/javascript"> 
<!-- 
var letter = "a"; 
if(letter == "a"){ 
    alert("Letter is A"); 
} else if(letter == "b"){ 
    alert("Letter is B"); 
} else if(letter == "c"){
    alert("Letter is C");
} 
//--> 
</script>

Example 2 - switch:
<script type="text/javascript"> 
<!-- 
var letter = "a"; 
switch(letter){ 
    case "a" : 
        alert("Letter is A"); 
        break; 
    case "b" : 
        alert("Letter is B"); 
        break; 
    case "c" : 
        alert("Letter is C"); 
        break; 
} 
//--> 
</script> 

Both scripts do exactly the same thing, only that the switch statement works by feeding the variable in and looks at the labels to see if there is a match. So instead of doing == to test the variable, you do case "XX" where XX would be the value to test against.

With the labels you need to terminate each one by using the "break" keyword, otherwise it will just skip that test on the variable. You can build up complex switch statements to run functions and perform other tasks.

Ok, so you have your switch statement testing a variable for a specific value, what if none of the tests match, and you want to allow for a default task to be performed if that is the case? Simple, we will use the "default" label to do this for us. Have a look at the example below, the script is exactly the same as above but we have included a default label to perform a task if all the matches return false.

<script type="text/javascript"> 
<!--
var letter = "a"; 
switch(letter){ 
    case "a" : 
        alert("Letter is A");
         break; 
    case "b" : 
        alert("Letter is B"); 
        break; 
    case "c" : 
        alert("Letter is C"); 
        break; 
    default :
        alert("Letter did not match");
 } 
//--> 
</script> 

With the above script we added the default label, so that at least something will get displayed. So if the variable "letter" does not match "a", "b", or "c", then it will alert the message "Letter did not match". If you notice with the default label, you do not need to provide the "break" keyword. So as you can see the switch statement can be very useful, I for one enjoy using it then do loads of if else statements. If you have a questions, feel free to post on the forum.