JavaScript


JavaScript Tutorial
JavaScript is the world's most popular programming language. It is the language for HTML, for the web, for servers, PCs, laptops, tablets, phones, and more. You can write directly to HTML
<script>
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
</script>
You will often see document.getElementById("some id"). This is defined in the HTML DOM. The DOM (Document Object Model) is the official W3C standard for accessing HTML elements. You will find several chapters about the HTML DOM in this tutorial.
<!DOCTYPE html>
<body>
<h1>My First JavaScript</h1>
<p id="demo">JavaScript can change the content of an HTML element.</p>
<script>
function myFunction()
{
x=document.getElementById("demo");  // Find the element
x.innerHTML="Hello JavaScript!";    // Change the content
}
</script>
<button type="button" onclick="myFunction()">Click Me!</button>
</body></html>
<!DOCTYPE html><html><head>
<script>
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script></head>
<body>
<h1>My First JavaScript</h1>
<p id="demo">This is a paragraph.</p>
<button type="button" onclick="displayDate()">Display Date</button>
</body></html>

JavaScript: Changing HTML Images

<!DOCTYPE html>
<body>
<script>
function changeImage()
{
element=document.getElementById('myimage')
if (element.src.match("bulbon"))
  {
  element.src="pic_bulboff.gif";
  } else {
  element.src="pic_bulbon.gif";
  }
}
</script>
<img id="myimage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">
<p>Click the light bulb to turn on/off the light</p></body></html>
To change the color of Text
function myfunction()
{
x=document.getElementById("demo")
x.style.color="red";
}

JavaScript Output

Manipulating HTML Elements

To access an HTML element from JavaScript, you can use the document.getElementById(id) method.
Use the "id" attribute to identify the HTML element:
<!DOCTYPE html><html><body>
<h1>My First Web Page</h1>
<p id="demo">My First Paragraph.</p>
<script>
document.getElementById("demo").innerHTML="My First JavaScript";
</script></body></html>

Writing to The Document Output

The example below writes a <p> element directly into the HTML document output:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
document.write("<p>My First JavaScript</p>");
</script></body></html>

Warning

Use document.write() only to write directly into the document output.
If you execute document.write after the document has finished loading, the entire HTML page will be overwritten:

Example

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.write("Oops! The document disappeared!");
}
</script>
</body></html>

JavaScript Statements

JavaScript is a sequence of statements to be executed by the browser. JavaScript statements are "commands" to the browser.
The purpose of the statements is to tell the browser what to do.
This JavaScript statement tells the browser to write "Hello Dolly" inside an HTML element with id="demo":
document.getElementById("demo").innerHTML="Hello Dolly";
You might see examples without semicolons.
Ending statements with semicolon is optional in JavaScript.

JavaScript Code

JavaScript code (or just JavaScript) is a sequence of JavaScript statements.Each statement is executed by the browser in the sequence they are written. This example will manipulate two HTML elements:
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";

JavaScript Code Blocks

JavaScript statements can be grouped together in blocks. Blocks start with a left curly bracket, and end with a right curly bracket. The purpose of a block is to make the sequence of statements execute together.  A good example of statements grouped together in blocks, are JavaScript functions.
function myFunction()
{
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
}

JavaScript is Case Sensitive

White Space

JavaScript ignores extra spaces. You can add white space to your script to make it more readable. The following lines are equivalent:
var person="Hege";
var person = "Hege";

Break up a Code Line

You can break up a code line within a text string with a backslash. The example below will be displayed properly:
document.write("Hello \
World!");
However, you cannot break up a code line like this:
document.write \
("Hello World!");

JavaScript Comments

Single line comments start with //.
Multi line comments start with /* and end with */.

JavaScript Data Types

When you assign a text value to a variable, put double or single quotes around the value.
When you assign a numeric value to a variable, do not put quotes around the value. If you put quotes around a numeric value, it will be treated as text.
var pi=3.14;
var person="John Doe";
var answer='Yes I am!';

One Statement, Many Variables

You can declare many variables in one statement. Just start the statement with var and separate the variables by comma:
var lastname="Doe", age=30, job="carpenter";           Your declaration can also span multiple lines:
var lastname="Doe",
age=30,
job="carpenter";

Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable, it will not lose its value:.
The value of the variable carname will still have the value "Volvo" after the execution of the following:
var carname="Volvo";
var carname;

JavaScript Data Types

String, Number, Boolean, Array, Object, Null, Undefined. JavaScript Has Dynamic Types

JavaScript has dynamic types. This means that the same variable can be used as different types:

Example

var x;               // Now x is undefined
var x = 5;           // Now x is a Number
var x = "John";      // Now x is a String

JavaScript Arrays

The following code creates an Array called cars:
var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
or (condensed array):
var cars=new Array("Saab","Volvo","BMW");
or (literal array):

Example

var cars=["Saab","Volvo","BMW"];
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.

JavaScript Objects

An object is delimited by curly braces. Inside the braces the object's properties are defined as name and value pairs (name : value). The properties are separated by commas:
var person={firstname:"John", lastname:"Doe", id:5566};
The object (person) in the example above has 3 properties: firstname, lastname, and id.
Spaces and line breaks are not important. Your declaration can span multiple lines:
var person={
firstname : "John",
lastname  : "Doe",
id        :  5566
};
You can address the object properties in two ways:
name=person.lastname;
name=person["lastname"];

Declaring Variables as Objects

When a variable is declared with the keyword "new", the variable is declared as an object:
var name = new String;
var x =    new Number;
var y =    new Boolean;

JavaScript Objects

Almost everything in JavaScript can be an Object: Strings, Functions, Arrays, Dates....
Objects are just data, with properties and methods.

Properties and Methods

Properties are values associated with objects.
Methods are actions that objects can perform.
The properties of the car include name, model, weight, color, etc.
All cars have these properties, but the property values differ from car to car.
The methods of the car could be start(), drive(), brake(), etc.
All cars have these methods, but they are performed at different times.

Objects in JavaScript:

In JavaScript, objects are data (variables), with properties and methods.
You create a JavaScript String object when you declare a string variable like this:
var txt = new String("Hello World");
 String objects have built-in properties and methods:
In object oriented languages, properties and methods are often called object members.

Creating JavaScript Objects

Almost "everything" in JavaScript can be objects. Strings, Dates, Arrays, Functions.... You can also create your own objects. This example creates an object called "person", and adds four properties to it:

person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";

Accessing Object Properties

The syntax for accessing the property of an object is:
objectName.propertyName
This example uses the length property of the String object to find the length of a string:
var message="Hello World!";
var x=message.length;
The value of x, after execution of the code above will be: 12.

Accessing Object Methods

You can call a method with the following syntax:
objectName.methodName()
This example uses the toUpperCase() method of the String object, to convert a text to uppercase:
var message="Hello world!";
var x=message.toUpperCase();
The value of x, after execution of the code above will be:   HELLO WORLD!

JavaScript Function Syntax

A function is written as a code block (inside curly { } braces), preceded by the function keyword:
function functionname()
{
some code to be executed
}
<!DOCTYPE html>
<body>
<p>Click the button to call a function with arguments</p>
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
</body></html>

Functions With a Return Value

Sometimes you want your function to return a value back to where the call was made.
This is possible by using the return statement.
When using the return statement, the function will stop executing, and return the specified value.

Syntax

function myFunction()
{
var x=5;
return x;
}

Local JavaScript Variables

A variable declared (using var) within a JavaScript function becomes LOCAL and can only be accessed from within that function. (the variable has local scope).
You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.
Local variables are deleted as soon as the function is completed.

Global JavaScript Variables

Variables declared outside a function, become GLOBAL, and all scripts and functions on the web page can access it.

The Lifetime of JavaScript Variables

The lifetime JavaScript variables starts when they are declared.
Local variables are deleted when the function is completed.
Global variables are deleted when you close the page.

Assigning Values to Undeclared JavaScript Variables

If you assign a value to variable that has not yet been declared, the variable will automatically be declared as a GLOBAL variable.
This statement:
carname="Volvo";

JavaScript Operators

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values. Given that y=5, the table below explains the arithmetic operators:
Operator
Description
Example
Result of x
Result of y
+
Addition
x=y+2
7
5
-
Subtraction
x=y-2
3
5
*
Multiplication
x=y*2
10
5
/
Division
x=y/2
2.5
5
%
Modulus (division remainder)
x=y%2
1
5
++
Increment
x=++y
6
6
x=y++
5
6
--
Decrement
x=--y
4
4
x=y--
5
4

JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables. Given that x=10 and y=5, the table below explains the assignment operators:
Operator
Example
Same As
Result
=
x=y

x=5
+=
x+=y
x=x+y
x=15
-=
x-=y
x=x-y
x=5
*=
x*=y
x=x*y
x=50
/=
x/=y
x=x/y
x=2
%=
x%=y
x=x%y
x=0

The + Operator Used on Strings

The + operator can also be used to add string variables or text values together.

Example

To add two or more string variables together, use the + operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
The result of txt3 will be:
What a verynice day
To add a space between the two strings, insert a space into one of the strings:

Example

txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2;
The result of txt3 will be:
What a very nice day
or insert a space into the expression:

Example

txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
The result of txt3 will be:
What a very nice day

Adding Strings and Numbers

Adding two numbers, will return the sum, but adding a number and a string will return a string:

Example

x=5+5;
y="5"+5;
z="Hello"+5;
The result of x,y, and z will be:
10
55
Hello5

JavaScript Comparison and Logical Operators

Comparison and Logical operators are used to test for true or false.

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between variables or values.
Given that x=5, the table below explains the comparison operators:
Operator
Description
Comparing
Returns
==
equal to
x==8
false
x==5
true
===
exactly equal to (equal value and equal type)
x==="5"
false
x===5
true
!=
 not equal
x!=8
true
!==
 not equal (different value or different type)
x!=="5"
true
x!==5
false
> 
 greater than
x>8
false
< 
 less than
x<8
true
>=
 greater than or equal to
x>=8
false
<=
 less than or equal to
x<=8
true

How Can it be Used

Comparison operators can be used in conditional statements to compare values and take action depending on the result:
if (age<18) x="Too young";
You will learn more about the use of conditional statements in the next chapter of this tutorial.

Logical Operators

Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
Operator
Description
Example
&&
and
(x < 10 && y > 1) is true
||
or
(x==5 || y==5) is false
!
not
!(x==y) is true

Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Syntax

variablename=(condition)?value1:value2 
If the variable age is a value below 18, the value of the variable voteable will be "Too young, otherwise the value of voteable will be "Old enough":
voteable=(age<18)?"Too young":"Old enough";



Conditional Statements

In JavaScript we have the following conditional statements:
  • if statement - use this statement to execute some code only if a specified condition is true
  • if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false
  • if...else if....else statement - use this statement to select one of many blocks of code to be executed
  • switch statement - use this statement to select one of many blocks of code to be executed

<!DOCTYPE html>
<head></head>
<body>
<p> Here small function for Welcome the user</p>
<p id="demo"></p>
<script>
function myday()
{
t=new Date().getHours();

if (t<12)
{
x = " Good Morning Dear User";
}
else if (t<17)
{
x = "Good Afternoon Dear User";
}
else if (t<24)
{
x= "Goodnight Dear User";
}
else
{
x= "I do not Know what to tell";
}
document.getElementById("demo").innerHTML=x;
}
document.getElementById("msg").innerHTML=myday();
</script>
<p id="msg"></p>
</body></html>

The JavaScript Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax

switch(n)
{
case 1:
  execute code block 1
  break;
case 2:
  execute code block 2
  break;
default:
  code to be executed if n is different from case 1 and 2
}
This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.

<!DOCTYPE html>

<head></head>

<body>

<p id="msg"></p>

<script>

function myswitch()

{

 var x;

 var n=new Date().getDay();

 switch (n)

 {

                case 0:

                 x= "Today Sunday";

                 break;

                case 1:

                 x="Today Monday";

                 break;

                case 2:

                 x="Today Tuesday";

                 break;

                case 3:

                 x="Today Wendensday";

                 break;

                case 4:

                 x="Today Thursday";

                 break;

                case 5:

                 x="Today Friday";

                 break;

                case 6:

                 x="Today Saturday";

                 break;

                default:

                x=" so funy I do not know what is Today";

 }

document.getElementById("msg").innerHTML=x;

}

document.getElementById("demo").innerHTML=myswitch();

</script>

<p id="demo"></p>

</body></html>

The default Keyword

Use the default keyword to specify what to do if there is no match: If it is NOT Saturday or Sunday, then write a default message:

JavaScript Loops

Loops are handy, if you want to run the same code over and over again, each time with a different value.
Often this is the case when working with arrays:

Instead of writing:

document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
<!DOCTYPE html>
<html>
<body>

<script>
cars=["BMW","Volvo","Saab","Ford"];
for (var i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
}
</script></body></html>

Different Kinds of Loops

JavaScript supports different kinds of loops:
  • for - loops through a block of code a number of times
  • for/in - loops through the properties of an object
  • while - loops through a block of code while a specified condition is true
  • do/while - also loops through a block of code while a specified condition is true

The For Loop

The for loop is often the tool you will use when you want to create a loop.
The for loop has the following syntax:
for (statement 1; statement 2; statement 3)
  {
  the code block to be executed
  }
Statement 1 is executed before the loop (the code block) starts.
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.
<!DOCTYPE html>
<body>
<p id="demo"></p>
<script>
var x ="";
for (i=0;i<5;i++)
{
     x= x + " The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
</script></body></html>
From the example above, you can read:
Statement 1 sets a variable before the loop starts (var i=0).
Statement 2 defines the condition for the loop to run (i must be less than 5).
Statement 3 increases a value (i++) each time the code block in the loop has been executed.

Statement 1

Normally you will use statement 1 to initiate the variable used in the loop (var i=0).
This is not always the case, JavaScript doesn't care, and statement 1 is optional.
You can initiate any (or many) values in statement 1:
for (var i=0,len=cars.length; i<len; i++)
{
document.write(cars[i] + "<br>");
}
And you can omit statement 1 (like when your values are set before the loop starts):

Example:

var i=2,len=cars.length;
for (; i<len; i++)
{
document.write(cars[i] + "<br>");
}

Statement 2

It is optional. If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser. Read about breaks in a later chapter of this tutorial.

Statement 3

Also is optional. The increment could be negative (i--), or larger (i=i+15). Statement 3 can also be omitted (like when you have corresponding code inside the loop):
var i=0,len=cars.length;
for (; i<len; )
{
document.write(cars[i] + "<br>");
i++;
}

The For/In Loop

The JavaScript for/in statement loops through the properties of an object:
<!DOCTYPE html>
<html>
<body>
<button onclick="myfunction()">try it</button>
<p id="demo"></p>
<script>
function myfunction()
{
  var x ;
  var txt = ""
  var person={fname:"yasser",job:"programmer",age:40};
  for (x in person)
  {
                txt =txt + person[x] + "<br>";
document.getElementById("demo").innerHTML=txt;
  }
}
</script></body></html>

JavaScript While Loop

Loops can execute a block of code as long as a specified condition is true.

The While Loop

The while loop loops through a block of code as long as a specified condition is true.
<!DOCTYPE html>
<body>
<button onclick="myfunction()">try it</button>
<p id="demo"></p>
<script>
function myfunction()
{
var x = "", i= 0;
while (i<5)
{
                x= x + " number is " + i + "<br>";
                i++;
}
document.getElementById("demo").innerHTML=x;
}
</script></body></html>
If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser.

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

Example

do
  {
  x=x + "The number is " + i + "<br>";
  i++;
  }
while (i<5);

The Break Statement

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch() statement.
The break statement can also be used to jump out of a loop.  
The break statement breaks the loop and continues executing the code after the loop (if any):
The break statement "jumps out" of a loop.
The continue statement "jumps over" one iteration in the loop.
for (i=0;i<10;i++)
  {
  if (i==3)
    {
    break;
    }
  x=x + "The number is " + i + "<br>";
  }

Since the if statement has only one single line of code, the braces can be omitted:
for (i=0;i<10;i++)
  {
  if (i==3) break;
  x=x + "The number is " + i + "<br>";
  }

The Continue Statement

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
This example skips the value of 3:

Example

for (i=0;i<=10;i++)
 {
 if (i==3) continue;
  x=x + "The number is " + i + "<br>";
  }

JavaScript Labels

As you have already seen, in the chapter about the switch statement, JavaScript statements can be labeled.
To label JavaScript statements you precede the statements with a colon:
label:
statements
The break and the continue statements are the only JavaScript statements that can "jump out of" a code block.
Syntax:
break labelname;
continue labelname;
The continue statement (with or without a label reference) can only be used inside a loop.
The break statement, without a label reference, can only be used inside a loop or a switch.
With a label reference, it can be used to "jump out of" any JavaScript code block:
<!DOCTYPE html>
<html>
<body>
<script>
cars=["BMW","Volvo","Saab","Ford"];
list:
{
document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
break list;
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
}
</script></body>

JavaScript Errors - Throw and Try to Catch

The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
When the JavaScript engine is executing JavaScript code, different errors can occur:
It can be syntax errors, typically coding errors or typos made by the programmer.
It can be misspelled or missing features in the language (maybe due to browser differences).
It can be errors due to wrong input, from a user, or from an Internet server.
And, of course, it can be many other unforeseeable things.

JavaScript Throws Errors

When an error occurs, when something goes wrong, the JavaScript engine will normally stop, and generate an error message.
The technical term for this is: JavaScript will throw an error.

JavaScript try and catch

The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The JavaScript statements try and catch come in pairs.
<!DOCTYPE html>
<html>
<body>
<button onclick="myfunction()">try it</button>
<script>
function myfunction()
{
            try
            {
            adddd("welcome guest!");
            }
            catch (err)
            {
            txt="There was an error on this page.\n\n";
            txt+="Error description: " + err.message + "\n\n";
            txt+="Click OK to continue.\n\n";
            alert(txt);
            }
}
</script></body></html>

The Throw Statement

The throw statement allows you to create a custom error. The correct technical term is to create or throw an exception. If you use the throw statement together with try and catch, you can control program flow and generate custom error messages. The exception can be a JavaScript String, a Number, a Boolean or an Object.
This example examines the value of an input variable. If the value is wrong, an exception (error) is thrown. The error is caught by the catch statement and a custom error message is displayed:
<!DOCTYPE html>
<body>
<script>
function myFunction()
{
 y=document.getElementById("mess");
    y.innerHTML="";
try
{
 x=document.getElementById("demo").value;
if(x=="")    throw "empty";
if(isNaN(x)) throw "not a number";
if(x>10)     throw "too high";
if(x<5)      throw "too low";
}
catch(err)
{
y.innerHTML="Error: " + err + ".";
}
}
</script>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="mess"></p>
</body>
</html>
Note that the example above will also throw an error if the getElementById function fails.

JavaScript Form Validation

JavaScript can be used to validate data in HTML forms before sending off the content to a server.
Form data that typically are checked by a JavaScript could be:
  • has the user left required fields empty?
  • has the user entered a valid e-mail address?
  • has the user entered a valid date?
  • has the user entered text in a numeric field?

Required Fields

The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false, and the form will not be submitted:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

E-mail Validation

The function below checks if the content has the general syntax of an email.
This means that the input data must contain an @ sign and at least one dot (.). Also, the @ must not be the first character of the email address, and the last dot must be present after the @ sign, and minimum 2 characters before the end:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
  alert("Not a valid e-mail address");
  return false;
  }
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form></body></html>

JavaScript Objects

"Everything" in JavaScript is an Object.
In addition, JavaScript allows you to define your own objects.

Everything is an Object

In JavaScript almost everything is an object. Even primitive datatypes (except null and undefined) can be treated as objects.
  • Booleans can be objects or primitive data treated as objects
  • Numbers can be objects or primitive data treated as objects
  • Strings are also objects or primitive data treated as objects
  • Dates are always objects
  • Maths and Regular Expressions are always objects
  • Arrays are always objects
  • Even functions are always objects

JavaScript Objects

An object is just a special kind of data, with properties and methods.

Accessing Object Properties

Properties are the values associated with an object.
The syntax for accessing the property of an object is:
objectName.propertyName
This example uses the length property of the String object to find the length of a string:
var message="Hello World!";
var x=message.length;
The value of x, after execution of the code above will be: 12

Accessing Objects Methods

Methods are the actions that can be performed on objects.
You can call a method with the following syntax:
objectName.methodName()
This example uses the toUpperCase() method of the String object, to convert a text to uppercase:
var message="Hello world!";
var x=message.toUpperCase();
The value of x, after execution of the code above will be: HELLO WORLD!

Creating JavaScript Objects

With JavaScript you can define and create your own objects.
There are 2 different ways to create a new object:
  • 1. Define and create a direct instance of an object.
  • 2. Use a function to define an object, then create new object instances.

Creating a Direct Instance

The following example creates a new instance of an object, and adds four properties to it:
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};

Using an Object Constructor

The following example uses a function to construct the object:
<!DOCTYPE html><html><body><script>
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
myFather=new person("John","Doe",50,"blue");
document.write(myFather.firstname + " is " + myFather.age + " years old.");
</script></body></html>
The reason for all the "this" stuff is that you're going to have more than one person at a time (which person you're dealing with must be clear). That's what "this" is: the instance of the object at hand.

Creating JavaScript Object Instances

Once you have a object constructor, you can create new instances of the object, like this:
var myFather=new person("John","Doe",50,"blue");
var myMother=new person("Sally","Rally",48,"green");

Adding Properties to JavaScript Objects

You can add new properties to an existing object by simply giving it a value.
Assume that the person object already exists - you can then give it new properties:
person.nationality="English";
x=person.nationality;
The value of x, after execution of the code above will be: English

Adding Methods to JavaScript Objects

Methods are just functions attached to objects.
Defining methods to an object is done inside the constructor function:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;

this.changeName=changeName;
function changeName(name)
{
this.lastname=name;
}
}
The changeName() function assigns the value of name to the person's lastname property.
<!DOCTYPE html><body><script>
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.changeName=changeName;
function changeName(name)
{
this.lastname=name;
}
}
myMother=new person("Sally","Rally",48,"green");
myMother.changeName("Doe");
document.write(myMother.lastname);
</script></body></html>
JavaScript knows which person you are talking about by "substituting" this with myMother.

JavaScript Classes

JavaScript is an object oriented language, but JavaScript does not use classes.
In JavaScript you don’t define classes and create objects from these classes (as in most other object oriented languages).
JavaScript is prototype based, not class based.

JavaScript for...in Loop

The JavaScript for...in statement loops through the properties of an object.

Syntax

for (variable in object)
  {
  code to be executed
  }
Note: The block of code inside of the for...in loop will be executed once for each property.
Looping through the properties of an object:
<!DOCTYPE html><html><body>
<p>Click the button to loop through the properties of an object named "person".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var txt="";
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
txt=txt + person[x];
}
document.getElementById("demo").innerHTML=txt;
}
</script></body></html>

JavaScript Numbers

JavaScript numbers can be written with, or without decimals:
Extra large or extra small numbers can be written with scientific (exponent) الاس notation:

Example

var y=123e5;    // 12300000
var z=123e-5;   // 0.00123

JavaScript Numbers are 64-bit Floating Point

JavaScript is not a typed language. Unlike many other programming languages, it does not define different types of numbers, like integers, short, long, floating-point etc.
JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.
This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:

Precision

Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.
The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:

Octal ثماني and Hexadecimal عشري

JavaScript interprets numeric constants as octal if they are preceded by a zero, and as hexadecimal if they are preceded by a zero and "x".
Never write a number with a leading zero, unless you want an octal conversion.
By default, Javascript displays numbers as base 10 decimals.
But you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).
<script>
var myNumber = 128;
document.write(myNumber + ' decimal<br>');
document.write(myNumber.toString(16) + ' hex<br>');
document.write(myNumber.toString(8) + ' octal<br>');
document.write(myNumber.toString(2) + ' binary<br>');
</script>

Infinity

If you calculate a number outside the largest number provided by Javascript, Javascript will return the value of Infinity or -Infinity (positive or negative overflow):
<script>
myNumber=2;
while (myNumber!=Infinity)
{
myNumber=myNumber*myNumber;
document.write(myNumber +'<BR>');
}
</script>
Division by 0 (zero) also generates Infinity:

NaN - Not a Number

NaN is JavaScript reserved word indicating that the result of a numeric operation was not a number.
You can use the global JavaScript function isNaN(value) to find out if a value is a number.
<script>
var x = 1000 / "Apple";
var y = 1000 / "1000";
document.getElementById("demo").innerHTML = isNaN(x) + "<br>" + isNaN(y);
</script>
Result will be true then false.

Numbers Can be Numbers or Objects

JavaScript numbers can be primitive بدائي values created from literals, like var x = 123;
JavaScript number can also be objects created with the new keyword, like var y = new Number(123);
<script>
var x = 123;              // x is a number
var y = new Number(123);  // y is an object
var txt = typeof(x) + " " + typeof(y);
document.getElementById("demo").innerHTML=txt;
</script>
Notes: typeof() define the type of variables;
Normally, because of some nasty side effects, you will not define numbers as objects.
<script>
var x = 123;              // x is a number
var y = new Number(123);  // y is an object
document.getElementById("demo").innerHTML = x===y;
</script>
Result: false

Number Properties

  • MAX_VALUE - MIN_VALUE - NEGATIVE_INFINITY -  POSITIVE_INFINITY – NaN – prototype -  constructor
All number properties are properties of JavaScripts' number object wrapper called Number. These properties can only be accesses as Number.MAX_VALUE. Using num.MAX_VALUE, where num is a created object or a primitive number value, will return undefined.

Number Methods

  • toExponential()
  • toFixed()
  • toPrecision()
  • toString()
  • valueOf()
Note: Primitive values, like 3.14, cannot have properties and methods (because they are not objects).
With JavaScript, all methods of the number object are also available to primitive values, because Javascript will temporarily transfer primitive values to objects before executing the methods.

 JavaScript Strings

A string simply stores a series of characters like "John Doe". You can use single or double quotes:

Example

var carname="Volvo XC60";
var carname='Volvo XC60';
You can access each character in a string with its position (index):

 Example

var character=carname[7];
 String indexes are zero-based, which means the first character is [0], the second is [1], and so on.
you can put quotes inside a string by using the \ escape character before the apostrophe :

Example

var answer='It\'s alright';
var answer="He is called \"Johnny\"";

String Length

The length of a string (a string object) is found in the built in property length:
var txt="Hello World!";
document.write(txt.length);
var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write(txt.length);

 Finding a String in a String

The indexOf() method returns the position (as a number) of the first found occurrence of a specified text inside a string:
 <script>
function myFunction()
{
var str=document.getElementById("p1").innerHTML;
var n=str.indexOf("welcome ");
document.getElementById("p2").innerHTML=n+1;
}
</script>
The method returns -1 if the specified text is not found.
The lastIndexOf() method starts searching at the end of the string instead of at the beginning.

Matching Content

The match() method can be used to search for a matching content in a string:
<!DOCTYPE html>
<html>
<body>
<script>
var str="Hello world!";
document.write(str.match("world") + "<br>");
document.write(str.match("World") + "<br>");
document.write(str.match("world!"));
</script>
</body>
</html>

Replacing Content

The replace() method replaces a specified value with another value in a string.

Example

str="Please visit Microsoft!"
var n=str.replace("Microsoft","W3Schools");

Upper Case and Lower Case

A string is converted to upper/lower case with the methods toUpperCase() / toLowerCase():

Example

var txt="Hello World!";       // String
var txt1=txt.toUpperCase();   // txt1 is txt converted to upper
var txt2=txt.toLowerCase();   // txt2 is txt converted to lower

Convert a String to an Array

A string is converted to an array with the built in method string.split():
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the array values after the split.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str="a,b,c,d,e,f";
var n=str.split(",");
document.getElementById("demo").innerHTML=n[0];
}
</script></body>

Special Characters

The backslash (\) can be used to insert apostrophes, new lines, quotes, and other special characters into a string.
Look at the following JavaScript code:
var txt="We are the so-called "Vikings" from the north.";
document.write(txt);
In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called To solve this problem, you must place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal:
var txt="We are the so-called \"Vikings\" from the north.";
document.write(txt);
JavaScript will now output the proper text string: We are the so-called "Vikings" from the north.
The table below lists other special characters that can be added to a text string with the backslash sign:
Code
Outputs
\'
single quote
\"
double quote
\\
backslash
\n
new line
\r
carriage return
\t
tab
\b
backspace
\f
form feed

Strings Can be Strings or Objects

JavaScript strings can be primitive values created from literals, like var x = "John";
JavaScript strings can also be objects created with the new keyword, like var y = new String("John");

Example

var x = "John";
var y = new String("John");
typeof(x) // returns String
typeof(y) // returns Object
Normally, because of some nasty side effects, you will not define strings as objects.

Example

var x = "John";           
var y = new String("John");
(x === y) // is false because x is a string and y is an object.
Note: Primitive values, like "John", cannot have properties or methods (because they are not objects).
With JavaScript, all methods and properties of the string object are also available to primitive values, because Javascript will temporarily transfer primitive values to objects before executing the methods or properties.

String Properties and Methods

Properties:
  • length
  • prototype
  • constructor
Methods:
  • charAt() - charCodeAt() - concat() - fromCharCode() - indexOf() - lastIndexOf() - localeCompare() - match() - replace() - search() - slice() - split() - substr() - substring() - toLowerCase() - toUpperCase() - toString() - trim()  - valueOf()

JavaScript Date Object

The Date object is used to work with dates and times.
To show today:
var d=new Date();
document.write(d);
To show full year:
function myFunction()
{
var d = new Date();
var x = document.getElementById("demo");
x.innerHTML=d.getFullYear();
}
getTime() getTime() returns the number of milliseconds since 01.01.1970.
setFullYear() How to use setFullYear() to set a specific date.
toUTCString() use toUTCString() to convert today's date (according to UTC) to a string.
getDay() Use getDay() and an array to write a weekday, and not just a number.
function myFunction()
{
var d = new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

var x = document.getElementById("demo");
x.innerHTML=weekday[d.getDay()];
}
Display a clock
How to display a clock on your web page.
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout(function(){startTime()},500);
}

function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
  }
return i;
}

Create a Date Object

The Date object is used to work with dates and times. & created with the Date() constructor.
There are four ways of initiating a date:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Most parameters above are optional. Not specifying, causes 0 to be passed in.
Once a Date object is created, a number of methods allow you to operate on it. Most methods allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the object, using either local time or UTC (universal, or GMT) time.
All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds.
Some examples of initiating a date:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)

Set Dates

We can easily manipulate the date by using the methods available for the Date object.
In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
And in the following example we set a Date object to be 5 days into the future:
var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
Note: If adding 5 days to date shifts the month or year, the changes are handled auto by the Date object itself!

Compare Two Dates

Date object is also used to compare 2 dates. this example compares today's date with the 14th January 2100:
var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();
if (x>today)
  {
  alert("Today is before 14th January 2100");
  }
else
  {
  alert("Today is after 14th January 2100");
  }

JavaScript Array Object

The Array object is used to store multiple values in a single variable.
var i;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (i=0;i<mycars.length;i++)
{
document.write(mycars[i] + "<br>");
}
You will find more examples at the bottom of this page.

What is an Array?

An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
var car1="Saab";
var car2="Volvo";
var car3="BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.

Create an Array

An array can be created in three ways.
The following code creates an Array object called myCars:
1: Regular:
var myCars=new Array();
myCars[0]="Saab";     
myCars[1]="Volvo";
myCars[2]="BMW";
2: Condensed:
var myCars=new Array("Saab","Volvo","BMW");
3: Literal:
var myCars=["Saab","Volvo","BMW"];

Access an Array

You refer to an element in an array by referring to the index number.
This statement access the value of the first element in myCars:
var name=myCars[0];
This statement modifies the first element in myCars:
myCars[0]="Opel";
[0] is the first element in an array. [1] is the second . . . . . (indexes start with 0)

You Can Have Different Objects in One Array

All JavaScript variables are objects. Array elements are objects. Functions are objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:
myArray[0]=Date.now;
myArray[1]=myFunction;
myArray[2]=myCars;

Array Methods and Properties

The Array object has predefined properties and methods:
var x=myCars.length             // the number of elements in myCars
var y=myCars.indexOf("Volvo")   // the index position of "Volvo"

JavaScript Math Object

The Math object allows you to perform mathematical tasks.
round()
function myFunction()
{
document.getElementById("demo").innerHTML=Math.round(2.5);
}
Result 3
Math.random();max()
function myFunction()
{
document.getElementById("demo").innerHTML=Math.max(5,10);
}
Math.min (5,10);

Math Object

The Math object allows you to perform mathematical tasks. It includes several mathematical constants and methods.
Syntax for using properties/methods of Math:
var x=Math.PI;
var y=Math.sqrt(16);
Note: Math is not a constructor. All properties and methods of Math can be called by using Math as an object without creating it. uses the floor() and random() methods of the Math object to return a random number between 0 and 10:
document.write(Math.floor(Math.random()*11));
The code above can result in the following output:
8

JavaScript RegExp Object

RegExp, is short for regular expression.

RegExp Object

A regular expression is an object that describes a pattern of characters.
Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text.

Syntax

var patt=new RegExp(pattern,modifiers);or more simply:
var patt=/pattern/modifiers;
  • pattern specifies the pattern of an expression
  • modifiers specify if a search should be global, case-sensitive, etc.

RegExp Modifiers

Modifiers are used to perform case-insensitive and global searches.
The i modifier is used to perform case-insensitive matching.
The g modifier is used to perform a global match (find all matches rather than stopping after the first match).
Do a case-insensitive search for "w3schools" in a string:
var str="Visit W3Schools";
var patt1=/w3schools/i;
<body>
<p id="demo">Click the button to do a case-insensitive search for "w3schools" in a string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
var result = str.match(patt1);
document.getElementById("demo").innerHTML=result;
}
</script>
My code:
I have 2 files one html another js
Html file:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="srch.js"></script>
Search For: <input type="text" id="mysrch" />
<button onclick="mysearch()">Search</button>
<form name="myform" action="#" method="post">
<textarea id="txt" row="10" cols="50">
Hello World I love you Javascript, i love you
</textarea>
</form>
</body>
</body>
Javascript file which I will call it from html file
function mysearch()
{
var x=document.getElementById("mysrch").value;
var y=document.getElementById("txt").value;

var result=y.match(x);
if (result)
{
            alert ("Yes! we found " + result);
}
else
{
            alert ("Sorry Dear neto");
}
}
Do a global search for "is":
<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to do a global search for "is" in a string.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var str = "Is this all there is?";
var patt1 = /is/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML=result;
}
</script>

</body>
</html>
Result : is,is
Do a global, case-insensitive search for "is":
var str="Is this all there is?";
var patt1=/is/gi;

test()

The test() method searches a string for a specified value, and returns true or false, depending on the result.
The following example searches a string for the character "e":

Example

var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
Since there is an "e" in the string, the output of the code above will be: true
note: to do new line inside alert + '\n' +
Example:
function mysearch()
{
var x=document.getElementById("mysrch").value;
var y=document.getElementById("txt").value;
var mytext = new RegExp(x);
var result=y.match(x);
var t=mytext.test(y);
if (result)
{
            alert ("Yes! we found " + result + '\n' + " The Test of Search " + t );
}
else
{
            alert ("Sorry Dear neto");
}
}

exec()

The exec() method searches a string for a specified value, and returns the text of the found value. If no match is found, it returns null.
The following example searches a string for the character "e":
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));

JavaScript HTML DOM

With the HTML DOM, JavaScript can access all the elements of an HTML document.
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:
With a programmable object model, JavaScript gets all the power it needs to create dynamic HTML:
  • JavaScript can change all the HTML elements in the page
  • JavaScript can change all the HTML attributes in the page
  • JavaScript can change all the CSS styles in the page
  • JavaScript can react to all the events in the page

What is the DOM?

The DOM is a W3C (World Wide Web Consortium اتحاد) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
  • Core DOM - standard model for all document types
  • XML DOM - standard model for XML documents
  • HTML DOM - standard model for HTML documents

What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It defines:
  • The HTML elements as objects
  • The properties of all HTML elements
  • The methods to access all HTML elements
  • The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

Finding HTML Elements

Often, with JavaScript, you want to manipulate HTML elements.
To do so, you have to find the elements first. There are a couple of ways to do this:
  • Finding HTML elements by id
  • Finding HTML elements by tag name
  • Finding HTML elements by class name
  • Finding HTML elements by HTML object collections

Finding HTML Elements by Id

The easiest way to find HTML elements in the DOM, is by using the element id.
This example finds the element with id="intro":
<!DOCTYPE html>
<body>
<p id="intro">Hello World!</p>
<p>This example demonstrates the <b>getElementById</b> method!</p>
<script>
x=document.getElementById("intro");
document.write("<p>The text from the intro paragraph: " + x.innerHTML + "</p>");
</script></body></html>
If the element is found, the method will return the element as an object (in x).
If the element is not found, x will contain null.

Finding HTML Elements by Tag Name

This example finds the element with id="main", and then finds all <p> elements inside "main":
<body>
<p>Hello World!</p>
<div id="main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method</p>
</div>
<script>
var x=document.getElementById("main");
var y=x.getElementsByTagName("p");
document.write('First paragraph inside "main" is ' + y[0].innerHTML);
</script></body>

Finding HTML Elements by Class Name

If you want to find all HTML elements with the same class name. Use this method:
document.getElementsByClassName("intro");
The example above returns a list of all elements with class="intro".
Finding elements by class name does not work in Internet Explorer 5,6,7, and 8.

Finding HTML Elements by HTML Object Collections

This example finds the form element with id="frm", in the forms collection, and displays all element values:
<body>
<form id="frm1" action="form_action.asp">
  First name: <input type="text" name="fname" value="Donald"><br>
  Last name: <input type="text" name="lname" value="Duck"><br>
  <input type="submit" value="Submit">
</form>
<p>Return the value of each element in the form:</p>
<script>
var x=document.getElementById("frm1");
for (var i=0;i<x.length;i++)
  {
  document.write(x.elements[i].value);
  document.write("<br>");
  }
</script>
</body>
The following HTML object collections are accesible:
·         document.anchors - document.forms - document.images - document.links –
document.images

<body>
<img border="0" src="klematis.jpg" width="150" height="113">
<img border="0" src="klematis2.jpg" width="152" height="128">
<p>Number of images:
<script>
document.write(document.images.length);
</script></p>
</body>
Document.anchor

<body>
<a name="html">HTML Tutorial</a><br>
<a name="css">CSS Tutorial</a><br>
<a name="xml">XML Tutorial</a><br>
<p>Number of anchors:
<script>
document.write(document.anchors.length);
</script>
</p>
</body>
Result will be: Number of anchors: 3

Document.link
<html>
<body>
<img src ="planets.gif" width="145" height="126" alt="Planets" usemap ="#planetmap">
<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun">
<area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury">
<area shape="                                                                                                                                                                  circle" coords="124,58,8" href="venus.htm" alt="Venus">
</map>
<p><a href="/js/">JavaScript Tutorial</a></p>
<p>Number of areas/links:
<script>
document.write(document.links.length);
</script></p>
</body>
</html>
The output of the code above will be: Number of areas/links: 4

Changing the HTML Output Stream

JavaScript can create dynamic HTML content:
Date: Wed Nov 06 2013 17:24:22 GMT+0200 (Egypt Standard Time)
In JavaScript, document.write() can be used to write directly to the HTML output stream:
<script>
document.write(Date());
</script>
Never use document.write() after the document is loaded. It will overwrite the document.

Changing HTML Content

The easiest way to modify the content of an HTML element is by using the innerHTML property.
To change the content of an HTML element, use this syntax:
document.getElementById(id).innerHTML=new HTML
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
</body>
This example changes the content of an <h1> element:
<h1 id="header">Old Header></h1>
<script>
document.getElementById("header").innerHTML="New Header";
</script>
Example explained:
  • The HTML document above contains an <h1> element with id="header"
  • We use the HTML DOM to get the element with id="header"
  • A JavaScript changes the content (innerHTML) of that element

Changing the Value of an Attribute

document.getElementById(id).attribute=new value
This example changes the value of the src attribute of an <img> element:
<body>
<button onclick="myimage()">Change Image</button>
<img src="../2.jpg" id="myimg">
<script>
function myimage()
{
                document.getElementById("myimg").src="../1.jpg";
}
</script>
</body>
Example explained:
  • The HTML document above contains an <img> element with id="image"
  • We use the HTML DOM to get the element with id="image"
  • A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg"

JavaScript HTML DOM - Changing CSS

Changing HTML Style

To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style
The following example changes the style of a <p> element:
document.getElementById("p1").style.color="blue";

Using Events

The HTML DOM allows you to execute code when an event occurs.
Events are generated by the browser when "things happen" to HTML elements:
  • An element is clicked on
  • The page has loaded
  • Input fields are changed
This example changes the style of the HTML element with id="id1", when the user clicks a button:
<body>
<button onclick="document.getElementById('p1').style.color='red'">Color</button>
<button onclick="document.getElementById
('p1').style.visibility='hidden'">Hide</button>
<button onclick="document.getElementById
('p1').style.visibility='visible'">Show</button>
<p id="p1">Hello World HTML DOM can change the style of paragraph CSS</p>
</body>
The Style object property categories:
To change the Background Image:
<head>
<script>
function displayResult()
{
document.body.style.background="#f3f3f3 url('img_tree.png') no-repeat right top";
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<br>
<button type="button" onclick="displayResult()">Set background</button>
</body>

JavaScript HTML DOM Events

Examples of HTML events:
  • When a user clicks the mouse
  • When a web page has loaded
  • When an image has been loaded
  • When the mouse moves over an element
  • When an input field is changed
  • When an HTML form is submitted
  • When a user strokes a key
In this example, the content of the <h1> element is changed when a user clicks on it:
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
In this example, a function is called from the event handler:
<head>
<script>
function changetext(id)
{
id.innerHTML="Ooops!";
}
</script>
</head>
<body>
<h1 onclick="changetext(this)">Click on this text!</h1>
</body>
To show date by using the even inside the element button
<button onclick="document.getElementById('p2').innerHTML=Date()">Date</button>
<body>
<p>Click the button to execute the <em>displayDate()</em> function.</p>
<button id="myBtn">Try it</button>
<script>
document.getElementById("myBtn").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
<p id="demo"></p>
</body>
In the example above, a function named displayDate is assigned to an HTML element with the id="myBtn".
The function will be executed when the button is clicked.

The onload and onunload Events

The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. The onload and onunload events can be used to deal with cookies.

Example

<body onload="checkCookies()">
<script>
function checkCookies()
{
if (navigator.cookieEnabled==true)
            {
            alert("Cookies are enabled")
            }
else
            {
            alert("Cookies are not enabled")
            }
}
</script>
<p>An alert box should tell you if your browser has enabled cookies or not.</p>
</body>

The onchange Event

The onchange event are often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will be called when a user changes the content of an input field.
<head>
<script>
function myFunction()
{
var x=document.getElementById("fname");
x.value=x.value.toUpperCase();
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
</body>

The onmouseover and onmouseout Events

onmouseover & onmouseout events used to trigger a function when the user mouses over, or out of an HTML element.

The onmousedown, onmouseup and onclick Events

The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is triggered.
<body>
<div onmousedown="mDown(this)" onmouseup="mUp(this)" style="background-color:#D94A38;width:90px;height:20px;padding:40px;">Click Me</div>
<script>
function mDown(obj)
{
obj.style.backgroundColor="#1ec5e5";
obj.innerHTML="Release Me"
}
function mUp(obj)
{
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You"
}
</script>
</body>
Onfocus event:
<head>
<script>
function myFunction(x)
{
x.style.background="yellow";
}
</script>
</head>
<body>
Enter your name: <input type="text" onfocus="myFunction(this)">
<p>When the input field gets focus, a function is triggered which changes the background-color.</p>
</body>

JavaScript HTML DOM Navigation

With the HTML DOM, you can navigate the node tree using node relationships.

Navigating Node Relationships

The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships. Parent nodes have children.
  • In a node tree, the top node is called the root (or root node)
  • Every node has exactly one parent, except the root (which has no parent)
  • A node can have any number of children
  • Siblings are nodes with the same parent (brothers or sisters)
The following image illustrates a part of the node tree and the relationship between the nodes:
<html>
  <head>
    <title>DOM Tutorial</title>
  </head>
  <body>
    <h1>DOM Lesson one</h1>
    <p>Hello world!</p>
  </body>
</html>
 From the HTML above:
  • The root node <html> has no parents
  • The parent node of the <head> and <body> nodes is the <html> node
  • The parent node of the "Hello world!" text node is the <p> node
and:
  • The <html> node has two child nodes: <head> and <body>
  • The <head> node has one child node: the <title> node
  • The <title> node also has one child node: the text node "DOM Tutorial"
  • The <h1> and <p> nodes are siblings and child nodes of <body>
and:
  • The <head> element is the first child of the <html> element
  • The <body> element is the last child of the <html> element
  • The <h1> element is the first child of the <body> element
  • The <p> element is the last child of the <body> element
You can use the node properties like parentNode, firstChild, and lastChild, to navigate in an HTML document structure.

Warning !

A common error in DOM processing is to expect an element node to contain text.
In this example: <title>DOM Tutorial</title>, the element node <title> does not contain text. It contains a text node with the value "DOM Tutorial".
The value of the text node can be accessed by the node's innerHTML property, or the nodeValue.

Child Nodes and Node Values

In addition to the innerHTML property, you can also use the childNodes and nodeValue properties to get the content of an element.
The following code gets the value of the <p> element with id="intro":
<body>
<p id="intro">Hello World!</p>
<script>
txt=document.getElementById("intro").childNodes[0].nodeValue;
document.write(txt);
</script>
</body>
In the example above, getElementById is a method, while childNodes and nodeValue are properties.
In this tutorial we use the innerHTML property. However, learning the method above is useful for understanding the tree structure and the navigation of the DOM.
Using the firstChild property is the same as using childNodes[0]:
<body>
<p id="intro">Hello World!</p>
<script>
txt=document.getElementById("intro").firstChild.nodeValue;
document.write(txt);
</script>
</body>

DOM Root Nodes

There are two special properties that allow access to the full document:
  • document.documentElement - The full document
  • document.body - The body of the document
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.body</b> property.</p>
</div>
<script>
alert(document.body.innerHTML);
</script>
</body>

JavaScript HTML DOM Elements (Nodes)

Adding and Removing Nodes (HTML Elements)

Creating New HTML Elements (Nodes)

To add a new element to the HTML DOM, create element node first, and then append it to an existing element.
<body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para=document.createElement("p");
var node=document.createTextNode("This is new.");
para.appendChild(node);
var element=document.getElementById("div1");
element.appendChild(para);
</script></body>

Example Explained  This code creates a new <p> element:

var para=document.createElement("p");
To add text to the <p> element, you must create a text node first. This code creates a text node:
var node=document.createTextNode("This is a new paragraph.");
Then you must append the text node to the <p> element:
para.appendChild(node);
Finally you must append the new element to an existing element.
This code finds an existing element:
var element=document.getElementById("div1");
This code appends the new element to the existing element:
element.appendChild(para);

Removing Existing HTML Elements

To remove an HTML element, you must know the parent of the element:

Example

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>

Example Explained 

This HTML document contains a <div> element with two child nodes (two <p> elements):
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
Find the element with id="div1":
var parent=document.getElementById("div1");
Find the <p> element with id="p1":
var child=document.getElementById("p1");
Remove the child from the parent:
parent.removeChild(child);
It would be nice to be able to remove an element without referring to the parent.
But sorry. The DOM needs to know both the element you want to remove, and its parent
Here is a common workaround: Find the child you want to remove, and use its parentNode property to find the parent:
var child=document.getElementById("p1");
child.parentNode.removeChild(child);

HTML DOM Node List

The getElementsByTagName() method returns a node list. A node list is an array of nodes.
The following code selects all <p> nodes in a document:
var x=document.getElementsByTagName("p");
The nodes can be accessed by index number. To access the second <p> you can write:
<body>
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<script>
x=document.getElementsByTagName("p");
document.write("The innerHTML of the second paragraph is: " + x[1].innerHTML);
</script>
</body>

HTML DOM Node List Length

The length property defines the number of nodes in a node-list.
You can loop through a node-list by using the length property:
<body>

<p>Hello World!</p>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>length</b> property.</p>
<script>
x=document.getElementsByTagName("p");
for (i=0;i<x.length;i++)
  {
  document.write(x[i].innerHTML);
  document.write("<br>");
  }
</script>
</body>
Example explained:
  1. Get all <p> element nodes
  2. For each <p> element, output the value of its text node

JavaScript Window - The Browser Object Model

The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.

The Browser Object Model (BOM)

There are no official standards for the Browser Object Model (BOM).
Since modern browsers have implemented (almost) the same methods and properties for JavaScript interactivity, it is often referred to, as methods and properties of the BOM.

The Window Object

The window object is supported by all browsers. It represent the browser's window.
All global JavaScript objects, functions, and variables automatically become members of the window object.
Global variables are properties of the window object.
Global functions are methods of the window object.
Even the document object (of the HTML DOM) is a property of the window object:
window.document.getElementById("header");
is the same as:
document.getElementById("header");

Window Size

Three different properties can be used to determine the size of the browser window (the browser viewport, NOT including toolbars and scrollbars).
For Internet Explorer, Chrome, Firefox, Opera, and Safari:
  • window.innerHeight - the inner height of the browser window
  • window.innerWidth - the inner width of the browser window
For Internet Explorer 8, 7, 6, 5:
  • document.documentElement.clientHeight
  • document.documentElement.clientWidth
  • or
  • document.body.clientHeight
  • document.body.clientWidth
A practical JavaScript solution (covering all browsers):
<body>
<p id="demo"></p>
<script>
var w=window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h=window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

x=document.getElementById("demo");
x.innerHTML="Browser inner window width: " + w + ", height: " + h + "."
</script>
</body>
The example displays the browser window's height and width: (NOT including toolbars/scrollbars)

Other Window Methods

Some other methods:
  • window.open() - window.close() - window.moveTo() - window.resizeTo()
<html>
<head>
<script>
function open_win()
{
window.open("http://www.w3schools.com");
}
</script>
</head>

<body>
<form>
<input type="button" value="Open Window" onclick="open_win()">
</form>
</body>
</html>

JavaScript Window Screen

The window.screen object can be written without the window prefix.
Some properties:
  • screen.availWidth - available screen width
  • screen.availHeight - available screen height

Window Screen Available Width

The screen.availWidth property returns the width of the visitor's screen, in pixels, minus interface features like the Windows Taskbar.
<script>
document.write("Available Width: " + screen.availWidth);
</script>

JavaScript Window Location

Window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.
The window.location object can be written without the window prefix.
Some examples:
  • location.hostname returns the domain name of the web host
  • location.pathname returns the path and filename of the current page
  • location.port returns the port of the web host (80 or 443)
  • location.protocol returns the web protocol used (http:// or https://)

Window Location Href: The location.href property returns the URL of the current page.

<script>
document.write(location.href);
</script>

Window Location Pathname

The location.pathname property returns the path name of a URL.
<script>
document.write(location.pathname);
</script>
The output of the code above is:      /js/js_window_location.asp

Window Location Assign: The location.assign() method loads a new document.

<script>
function newDoc()
  {
  window.location.assign("http://www.w3schools.com")
  }
</script>
</head>
<body>
<input type="button" value="Load new document" onclick="newDoc()">
</body>

JavaScript Window History

The window.history object contains the browsers history. Can be written without the window prefix.
To protect the privacy of the users, there are limitations to how JavaScript can access this object.
Some methods:
  • history.back() - same as clicking back in the browser - history.forward() - same as clicking forward in the browser
The history.back() method loads the previous URL in the history list.
This is the same as clicking the Back button in the browser. Create a back button on a page:
<head>
<script>
function goBack()
  {
  window.history.back()
  }
</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()">
</body>
The output of the code above will be:
The same will be for forward
function goForward()
  {
  window.history.forward()
  }

JavaScript Window Navigator

The window.navigator object contains information about the visitor's browser.
The window.navigator object can be written without the window prefix.
<body>
<div id="example"></div>
<script>

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Browser Language: " + navigator.language + "</p>";
txt+= "<p>Browser Online: " + navigator.onLine + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";

document.getElementById("example").innerHTML=txt;
</script>
</body>

Warning !!!

The information from the navigator object can often be misleading, and should not be used to detect browser versions because:
  • The navigator data can be changed by the browser owner - Some browsers misidentify themselves to bypass site tests
  • Browsers cannot report new operating systems, released later than the browser

Browser Detection

Since the navigator object can be misleading about browser detection, using object detection can be used to sniff out different browsers.
Since different browsers support different objects, you can use objects to detect browsers. For example, since only Opera supports the property "window.opera", you can use that to identify Opera.
Example: if (window.opera) {...some action...}

JavaScript Popup Boxes

Confirm Box

often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
<body>
<p>Click the button to display a confirm box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var r=confirm("Press a button!");
if (r==true)
  {
  x="You pressed OK!";
  }
else
  {
  x="You pressed Cancel!";
  }
document.getElementById("demo").innerHTML=x;
}
</script></body>

Prompt Box

often used if you want the user to input a value before entering a page. When pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value.
window.prompt("sometext","defaultvalue");
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var person=prompt("Please enter your name","Harry Potter");
if (person!=null)
  {
  x="Hello " + person + "! How are you today?";
  document.getElementById("demo").innerHTML=x;
  }
}
</script>
</body>



JavaScript Timing Events

With JavaScript, it is possible to execute some code at specified time-intervals. This is called timing events.
It's very easy to time events in JavaScript. The two key methods that are used are:
  • setInterval() - executes a function, over and over again, at specified time intervals
  • setTimeout() - executes a function, once, after waiting a specified number of milliseconds
Note: The setInterval() and setTimeout() are both methods of the HTML DOM Window object.

The setInterval() Method

The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.

Syntax

window.setInterval("javascript function",milliseconds);
The window.setInterval() method can be written without the window prefix. The first parameter of setInterval() should be a function. The second parameter indicates the length of the time-intervals between each execution.
Note: There are 1000 milliseconds in one second.

Example: Alert "hello" every 3 seconds:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<p>After clicking away the alert box, an new alert box will appear in 3 seconds. This goes on forever...</p>
<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
setInterval(function(){alert("Hello")},3000);
}
</script>

</body>
</html>
The example show you how the setInterval() method works, but it is not very likely that you want to alert a message every 3 seconds.
Below is an example that will display the current time. The setInterval() method is used to execute the function once every 1 second, just like a digital watch.
<!DOCTYPE html>
<html>
<body>

<p>A script on this page starts this clock:</p>
<p id="demo"></p>

<script>
var myVar=setInterval(function(){myTimer()},1000);

function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}
</script>

</body>
</html>

How to Stop the Execution?

The clearInterval() method is used to stop further executions of the function specified in the setInterval() method.

Syntax

window.clearInterval(intervalVariable)
The window.clearInterval() method can be written without the window prefix.
To be able to use the clearInterval() method, you must use a global variable when creating the interval method:
myVar=setInterval("javascript function",milliseconds);
Then you will be able to stop the execution by calling the clearInterval() method.
<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>

<script>
var myVar=setInterval(function(){myTimer()},1000);
function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}
function myStopFunction()
{
clearInterval(myVar);
}
</script>

The setTimeout() Method

Syntax

window.setTimeout("javascript function",milliseconds);
The window.setTimeout() method can be written without the window prefix.
The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.
The first parameter of setTimeout() should be a function.
The second parameter indicates how many milliseconds, from now, you want to execute the first parameter.

Example

Wait 3 seconds, then alert "Hello":
<body>
<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
setTimeout(function(){alert("Hello")},3000);
}
</script>
</body>

JavaScript Cookies

A cookie is often used to identify a user.

What is a Cookie?

A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.
Examples of cookies:
  • Name cookie - The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like "Welcome John Doe!" The name is retrieved from the stored cookie
  • Date cookie - The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like "Your last visit was on Tuesday August 11, 2005!" The date is retrieved from the stored cookie

Create and Store a Cookie

In this example we will create a cookie that stores the name of a visitor. The first time a visitor arrives to the web page, he or she will be asked to  fill in her/his name. The name is then stored in a cookie. The next time the visitor arrives at the same page, he or she will get welcome message.
First, we create a function that stores the name of the visitor in a cookie variable:
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
The parameters of the function above hold the name of the cookie, the value of the cookie, and the number of days until the cookie expires.
In the function above we first convert the number of days to a valid date, then we add the number of days until the cookie should expire. After that we store the cookie name, cookie value and the expiration date in the document.cookie object.

Get a Cookie Value

Then, we create another function that returns the value of a specified cookie:
function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
  {
  c_start = c_value.indexOf(c_name + "=");
  }
if (c_start == -1)
  {
  c_value = null;
  }
else
  {
  c_start = c_value.indexOf("=", c_start) + 1;
  var c_end = c_value.indexOf(";", c_start);
  if (c_end == -1)
  {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
The code above uses the indexOf() method to search for a cookie name inside the document's cookie string.
The first indexOf() method will return the position where the cookie is found. The " " + and +"=" is added so that the method don't find names or values containing the name.
If the method returns -1, the cookie may still exist at the very beginning of the cookie string. To eliminate this, another search is added, this time without the " " +.

Check a Cookie Value

Last, we create the function that displays a welcome message if the cookie is set, and if the cookie is not set it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function:
function checkCookie()
{
var username=getCookie("username");
  if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}
All together now:
<!DOCTYPE html>
<head>
<script>
function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
  {
  c_start = c_value.indexOf(c_name + "=");
  }
if (c_start == -1)
  {
  c_value = null;
  }
else
  {
  c_start = c_value.indexOf("=", c_start) + 1;
  var c_end = c_value.indexOf(";", c_start);
  if (c_end == -1)
    {
    c_end = c_value.length;
    }
  c_value = unescape(c_value.substring(c_start,c_end));
  }
return c_value;
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
Some explanation about this code:

JavaScript escape() Function  It is a global function to Encode a string:

 ((exdays==null) ? "" : "; expires="+exdate.toUTCString());

it is codition on one line separator is : and mean that if exdays null will write “” and if not will write ; expires = and exdate +356.

 c_value.indexOf(";", c_start);  mean that indexOf will return the position of “;” start to search from c_start position. For example
var xx=”hello Yasser of Egypt”;
xx.indexOf(“e”,3);
that is mean indexOf will start to search about “e” from character number 3.

JavaScript Libraries

JavaScript libraries - jQuery, Prototype, MooTools.

JavaScript Frameworks (Libraries)

Advanced JavaScript programming (especially the complex handling of browser differences), can often be very difficult and time-consuming to work with.
To deal with these difficulties, a lot of JavaScript (helper) libraries have been developed.
These JavaScript libraries are often called JavaScript frameworks.
In this tutorial, we will take a look at some of the most popular JavaScript frameworks:
  • jQuery
  • Prototype
  • MooTools
All of these frameworks have functions for common JavaScript tasks like animations, DOM manipulation, and Ajax handling. In this tutorial we will teach you how start using them, to make JavaScript programming easier and safer

jQuery: jQuery is the most popular JavaScript framework on the Internet today.

It uses CSS selectors to access and manipulate HTML elements (DOM Objects) on a web page.
jQuery also provides a companion UI (user interface) framework and numerous other plug-ins.
Many of the largest companies on the Web use jQuery:
  • Google – Microsoft – IBM - Netflix

Prototype

Prototype is a JavaScript library that provides a simple API to perform common web tasks.
API is short for Application Programming Interface. It is a library of properties and methods for manipulating the HTML DOM.
Prototype enhances JavaScript by providing classes and inheritance.

MooTools

MooTools is also a framework that offers an API to make common JavaScript programming easier.
MooTools also includes some lightweight effects and animation functions.

Other Frameworks

Here are some other frameworks not covered in this short overview:
YUI - The Yahoo! User Interface Framework is a large library that covers a lot of functions, from simple JavaScript utilities to complete internet widgets.
Ext JS - Customizable widgets for building rich Internet applications.
Dojo - A toolkit designed around packages for DOM manipulation, events, widgets, and more.
script.aculo.us - Open-source JavaScript framework for visual effects and interface behaviors.
UIZE - Widgets, AJAX, DOM, templates, and more.

CDN - Content Delivery Networks

You always want your web pages to be as fast as possible. You want to keep the size of your pages as small as possible, and you want the browser to cache as much as possible.
If many different web sites use the same JavaScript framework, it makes sense to host the framework library in a common location for every web page to share.
A CDN (Content Delivery Network) solves this. A CDN is a network of servers containing shared code libraries.

Google provides a free CDN for a number of JavaScript libraries, including:
  • jQuery -  Prototype – MooTools – Dojo - Yahoo! YUI
To use a JavaScript framework library in your web pages, just include the library in a <script> tag:

Including jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>

Using Frameworks

Before you decide to use a JavaScript framework for your web pages, it might be a good idea to test the framework first.
JavaScript frameworks are very easy to test. You don't have to install them on your computer, and there are no setup programs.
Normally you just have to reference a library file from your web page.

JavaScript - Testing jQuery

Including jQuery

To test a JavaScript library, you need to include it in your web page.
To include a library, use the <script> tag with the src attribute set to the URL of the library:

Including jQuery

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
</head>
<body>
</body>
</html>

jQuery Described

The main jQuery function is the $() function (the jQuery function). If you pass DOM objects to this function, it returns jQuery objects, with jQuery functionality added to them.
jQuery allows you to select elements by CSS selectors.
In JavaScript, you can assign a function to handle the window's load event:

The JavaScript Way:

function myFunction()
{
var obj=document.getElementById("h01");
obj.innerHTML="Hello jQuery";
}
onload=myFunction;
The jQuery equivalent is different:

The jQuery Way:

function myFunction()
{
$("#h01").html("Hello jQuery");
}
$(document).ready(myFunction);
The last line of the code above, passes the HTML DOM document object to jQuery: $(document).
When you pass DOM objects to jQuery, jQuery returns new jQuery objects wrapped around the HTML DOM objects.
The jQuery function returns a new jQuery object, where ready() is a method.
Since functions are variables in JavaScript, myFunction can be passed as a variable to the jQuery ready method. 

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
function myFunction()
{
$("#h01").attr("style","color:red").html("Hello jQuery")
}
$(document).ready(myFunction);
</script>
</head>
<body>
<h1 id="h01"></h1>
</body>
</html>
As you can see from the example above, jQuery allows chaining.
Chaining is a handy way to perform multiple tasks on one object.

JavaScript - Testing Prototype

Including Prototype

To include a library, use the <script> tag with the src attribute set to the URL of the library:

Including Prototype

<!DOCTYPE html>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/
prototype/1.7.1.0/prototype.js>
</script>
</head>
<body>
</body>
</html>

Prototype Described

Prototype provides functions to make HTML DOM programming easier.
Like jQuery, Prototype has its $() function.
The $() function accepts HTML DOM element id values (or DOM elements), and adds new functionality to DOM objects.
Unlike jQuery, Prototype has no ready() method to take the place of window.onload(). Instead, Prototype adds extensions to the browser and the HTML DOM.

The Prototype Way:

function myFunction()
{
$("h01").insert("Hello Prototype!");
}
Event.observe(window,"load",myFunction);
Event.observe() accepts three arguments:
  • The HTML DOM or BOM (Browser Object Model) object you want to handle
  • The event you want to handle
  • The function you want to call
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/
prototype/1.7.1.0/prototype.js">
</script>
<script>
function myFunction()
{
$("h01").writeAttribute("style","color:red").insert("Hello Prototype!");
}
Event.observe(window,"load",myFunction);
</script>
</head>
<body>
<h1 id="h01"></h1>
</body>
</html>
As you can see from the example above, like jQuery, Prototype allows chaining.
Chaining is a handy way to perform multiple tasks on one object.

JavaScript Global Properties

Property
Description
A numeric value that represents positive/negative infinity
"Not-a-Number" value
Indicates that a variable has not been assigned a value

JavaScript Global Functions

Function
Description
Decodes a URI
Decodes a URI component
Encodes a URI
Encodes a URI component
Deprecated in version 1.5. Use encodeURI() or encodeURIComponent() instead
Evaluates a string and executes it as if it was script code
Determines whether a value is a finite, legal number
Determines whether a value is an illegal number
Converts an object's value to a number
Parses a string and returns a floating point number
Parses a string and returns an integer
Converts an object's value to a string
Deprecated in version 1.5. Use decodeURI() or decodeURIComponent() instead

Decode a URI after encoding it:


<body>
<p id="demo">Click the button to decode a URI after encoding it.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var uri = "my test.asp?name=ståle&car=saab";
var enc = "Encoded URI: " + encodeURI(uri);
var dec = "Decoded URI: " + decodeURI(uri);
var res = enc + "<br>" + dec;
document.getElementById("demo").innerHTML=res;
}
</script>
</body>

6 comments: