Welcome! If you like our Blog so please Follow this blog and also +1 this blog here---->
Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Tuesday, 18 September 2012

Javascript Tutorial 5: JavaScript Popup Boxes and Throw Statement (Last)

JavaScript Popup Boxes


JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

Alert Box

An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.

Syntax

alert("sometext");

Example

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("I am an alert box!");
}
</script>
</head>
<body>

<input type="button" onclick="myFunction()" value="Show alert box" />

</body>
</html>


Confirm Box

A confirm box is 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.

Syntax

confirm("sometext");

Example

var r=confirm("Press a button");
if (r==true)
  {
  x="You pressed OK!";
  }
else
  {
  x="You pressed Cancel!";
  }


Prompt Box

A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box 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. If the user clicks "Cancel" the box returns null.

Syntax

prompt("sometext","defaultvalue");

Example

var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
  {
  x="Hello " + name + "! How are you today?";
  }


Line Breaks

To display line breaks inside a popup box, use a back-slash followed by the character n.

Example

alert("Hello\nHow are you?");

JavaScript Throw Statement

The throw statement allows you to create an exception.

The Throw Statement

The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages.

Syntax

throw exception
The exception can be a string, integer, Boolean or an object.
Note that throw is written in lowercase letters. Using uppercase letters will generate a JavaScript error!

Example

The example below determines the value of a variable called x. If the value of x is higher than 10, lower than 5, or not a number, we are going to throw an error. The error is then caught by the catch argument and the proper error message is displayed:

Example

<!DOCTYPE html>
<html>
<body>
<script>
var x=prompt("Enter a number between 5 and 10:","");
try
  {
  if(x>10)
    {
    throw "Err1";
    }
  else if(x<5)
    {
    throw "Err2";
    }
  else if(isNaN(x))
    {
    throw "Err3";
    }
  }
catch(err)
  {
  if(err=="Err1")
    {
    document.write("Error! The value is too high.");
    }
  if(err=="Err2")
    {
    document.write("Error! The value is too low.");
    }
  if(err=="Err3")
    {
    document.write("Error! The value is not a number.");
    }
  }
</script>
</body>
</html>
:if>

Monday, 17 September 2012

Javascript Tutorial 5: JavaScript Data Types and Objects

JavaScript Data Types

String, Number, Boolean, Array, Object, Null, Undefined.

JavaScript Strings

A string is a variable which stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use simple or double quotes:

Example

var carname="Volvo XC60";
var carname='Volvo XC60';
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

Example

var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
Or you can put quotes inside a string by using the \ escape character:

Example

var answer='It\'s alright';
var answer="He is called \"Johnny\"";
You can access each characters in a string with [position]:

Example

var character=carname[7];
String indexes are zero-based, which means the first character is [0], the second is [1], and so on.

JavaScript Numbers

JavaScript has only one type of number.
Numbers can be with, or without decimals:

Example

var pi=3.14;
var x=34;
The maximum number of decimals is 17.
Extra large or extra small numbers can be written with scientific notation:

Example

var y=123e5;    // 12300000
var z=123e-5;   // 0.00123
JavaScript arithmetic is not 100% accurate:

Example

var x=0.2+0.1;


JavaScript Booleans

Booleans can have only two values: true or false.
var x=true
var y=false
Booleans are often used in conditional testing. You will learn more about conditional testing in a later chapter of this tutorial.

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):
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: fistname, 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:

Example

name=person.lastname;
name=person["lastname"];


Null or Undefined

Non-existing is the value of a variable with no value.
Variables can be emptied by setting the value to null;
cars=null;
person=null;


Declaring Variable Types

When you declare a new variable, you can declare its type using the "new" keyword:
var carname=new String;
var x=      new Number;
var y=      new Boolean;
var cars=   new Array;
var person= new Object;

JavaScript Data Types

Almost everything in JavaScript is an Object: String, Number, Array, Function....
In addition, JavaScript allows you to define your own objects.

JavaScript Objects

JavaScript has several built-in objects, like String, Date, Array, and more.
An object is just a special kind of data, with properties and methods.

Objects 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

Real Life Illustration

A person is an object.
The persons' properties include name, height, weight, age, skin tone, eye color, etc.
All persons have these properties, but the values of those properties differ from person to person.

Objects Have 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!

Real Life Illustrated

A person is an object.
The persons' methods could be eat(), sleep(), work(), play(), etc.
All persons have these methods.

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

This example creates a new instance of an object, and adds four properties to it:
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";
Alternative syntax (using object literals):

Example

personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};


Using an Object Constructor

This example uses a function to construct the object:

Example

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
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.

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.

Now You Can Try:

myMother.changeName("Doe");
JavaScript knows which person you are talking about by "substituting" this with myMother.

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 personObj already exists - you can give it new properties named firstname, lastname, age, and eyecolor as follows:
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=30;
personObj.eyecolor="blue";

x=personObj.firstname;
The value of x, after execution of the code above will be:
John
:if>

Javascript Tutorial 4: JavaScript Variables and Functions

JavaScript Variables

Variables are "containers" for storing information:

JavaScript Data Types

var answer1="He is called 'Johnny'";
var answer2='He is called "Johnny"';var pi=3.14;

var x=123;
var y=123e5;
var z=123e-5;
var cars=new Array("Saab","Volvo","BMW");
var person={firstname:"John", lastname:"Doe", id:5566};


Like School Algebra

Remember algebra from school?
x=5
y=6
z=x+y
Do you remember that letters (like x) can be used to hold a value (like 5), and that you can use the information above to calculate the value of z to be 11?
These letters are called variables, and variables can be used to hold values (x=5).

JavaScript Variables

As with algebra, JavaScript variables are used to hold values or expressions.
Variable can have a short names, like x and y, or more descriptive names, like age, sum, or, totalvolume.
JavaScript variables can also be used to hold text values, like: name="John Doe".
Here are the rules for JavaScript variable names:
  • Variable names are case sensitive (y and Y are two different variables)
  • Variable names must begin with a letter, the $ character, or the underscore character

Declaring (Creating) JavaScript Variables

Creating a variable in JavaScript is most often referred to as "declaring" a variable.
You declare JavaScript variables with the var keyword:
var carname;
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign:
carname="Volvo";
However, you can also assign a value to the variable when you declare it:
var carname="Volvo";
In the example below we create a variable called carname, assigns the value "Volvo" to it, and put the value inside the HTML paragraph with id="demo":

Example

<p id="demo"></p>
var carname="Volvo";
document.getElementById("demo").innerHTML=carname;


JavaScript Data Types

There are many types of JavaScript variables, but for now, just think of two types: text and numbers.
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.

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 name="Doe", age=30, job="carpenter";
Your declaration can also span multiple lines:
var name="Doe",
age=30,
job="carpenter";


Value = undefined

In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. Variable declared without a value will have the value undefined.
The variable carname will have the value undefined after the execution of the following statement:
var carname;


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 two statements:
var carname="Volvo";
var carname;


JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:

Example

y=5;
x=y+2;
You will learn more about JavaScript operators in a later chapter of this tutorial.

JavaScript Functions

A function can be executed by an event, like clicking a button.

JavaScript Functions

A function is a block of code that executes only when you tell it to execute.
It can be when an event occurs, like when a user clicks a button, or from a call within your script, or from a call within another function.
Functions can be placed both in the <head> and in the <body> section of a document, just make sure that the function exists, when the call is made.

How to Define a Function

Syntax

function functionname()
{
some code
}
The { and the } defines the start and end of the function.
Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name.

JavaScript Function Example

Example

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}

</script>
</head>

<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
The function is executed when the user clicks the button.
You will learn more about JavaScript events in the JS Events chapter.

Calling a Function with Arguments

When you call a function, you can pass along some values to it, these values are called argumentsor parameters.
These arguments can be used inside the function.
You can send as many arguments as you like, separated by commas (,)
myFunction(argument1,argument2)
Declare the argument, as variables, when you declare the function:
function myFunction(var1,var2)
{
some code
}
The variables and the arguments must be in the expected order. The first variable is given the value of the first passed argument etc.

Example

<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
The function above will alert "Welcome Harry Potter, the Wizard" when the button is clicked.
The function is flexible, you can call the function using different arguments, and different welcome messages will be given:

Example

<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
<button onclick="myFunction('Bob','Builder')">Try it</button>
The example above will alert "Welcome Harry Potter, the Wizard" or "Welcome Bob, the Builder" depending on which button is clicked.

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;
}
The function above will return the value 5.
Note: It is not the entire JavaScript that will stop executing, only the function. JavaScript will continue executing code, where the function-call was made from.
The function-call will be replaced with the returnvalue:
var myVar=myFunction();
The variable myVar holds the value 5, which is what the function "myFunction()" returns.
You can also use the returnvalue without storing it as a variable:
document.getElementById("demo").innerHTML=myFunction();
The innerHTML of the "demo" element will be 5, which is what the function "myFunction()" returns.
You can make a returnvalue based on arguments passed into the function:

Example

Calculate the product of two numbers, and return the result:
function myFunction(a,b)
{
return a*b;
}

document.getElementById("demo").innerHTML=myFunction(4,3);
The innerHTML of the "demo" element will be:
12

function myFunction(a,b)
{
if (a>b)
  {
  return;
  }
x=a+b
}
The function above will exit the function if a>b, and will not calculate the sum of a and b.

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";
will declare the variable carname as a global variable , even if it is executed inside a function.

:if>

Javascript Tutorial 3: JavaScript Statement and Comments

JavaScript Statement

JavaScript is a sequence of statements to be executed by the browser.

JavaScript Statements

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";


Semicolon ;

Semicolon separates JavaScript statements.
Normally you add a semicolon at the end of each executable statement.
Using semicolons also makes it possible to write many statements on one line.

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:

Example

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.
An good example of statements grouped together in blocks, are JavaScript functions.
This example will run a function that will manipulate two HTML elements:

Example

function myFunction()
{
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
}
You will learn more about functions in later chapters.

JavaScript is Case Sensitive

JavaScript is case sensitive.
Watch your capitalization closely when you write JavaScript statements:
A function getElementById is not the same as getElementbyID.

A variable named myVariable is not the same as MyVariable.

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 name="Hege";
var name = "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

JavaScript comments can be used to make the code more readable.

JavaScript Comments

Comments will not be executed by JavaScript.
Comments can be added to explain the JavaScript, or to make the code more readable.
Single line comments start with //.
The following example uses single line comments to explain the code:

Example

// Write to a heading:
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
// Write to a paragraph:
document.getElementById("myP").innerHTML="This is my first paragraph.";


JavaScript Multi-Line Comments

Multi line comments start with /* and end with */.
The following example uses a multi line comment to explain the code:

Example

/*
The code below will write
to a heading and to a paragraph,
and will represent the start of
my homepage:
*/
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";


Using Comments to Prevent Execution

In the following example the comment is used to prevent the execution of one of the codelines (can be suitable for debugging):

Example

//document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
In the following example the comment is used to prevent the execution of a code block (can be suitable for debugging):

Example

/*
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
*/


Using Comments at the End of a Line

In the following example the comment is placed at the end of a code line:

Example

var x=5;    // declare x and assign 5 to it
var y=x+2;  // declare y and assign x+2 to it
:if>

Sunday, 16 September 2012

Javascript Tutorial 2: JavaScript How To and Where To

How To

A JavaScript is surrounded by a <script> and </script> tag.
JavaScript is typically used to manipulate HTML elements.

The <script> Tag

To insert a JavaScript into an HTML page, use the <script> tag.
The <script> and </script> tells where the JavaScript starts and ends.
The lines between the <script> and </script> contain the JavaScript:
<script>
alert("My First JavaScript");
</script>
You don't have to understand the code above. Just take it for a fact, that the browser will interpret and execute the JavaScript code between the <script> and </script> tags. 

Writing to The Document Output

The example below writes a <p> element directly into the HTML document output:

Example

<!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.

Where To

A JavaScript can be put in the <body> and in the <head> section of an HTML page.

JavaScript in <body>

The example below manipulate the content of an existing <p> element when the page loads:

Example

<!DOCTYPE html>
<html>
<body><h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<script>
document.getElementById("demo").innerHTML="My First JavaScript";
</script>

</body>
</html>


JavaScript Functions and Events

The JavaScript statement in the example above, is executed when the page loads, but that is not always what we want.
Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button. Then we can write the script inside a function, and call the function when the event occurs.
You will learn more about JavaScript functions and events in later chapters.

A JavaScript Function in <head>

The example below calls a function in the <head> section when a button is clicked:

Example

<!DOCTYPE html>
<html><head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>

</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>


A JavaScript Function in <body>

This example also calls a function when a button is clicked, but the function is in the <body>:

Example

<!DOCTYPE html>
<html>
<body><h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>

</body>
</html>



:if>