JavaScript and DHTML

Introduction to JavaScript
JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and much more.
JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, and Opera.

What is JavaScript?
•JavaScript was designed to add interactivity to HTML pages
•JavaScript is a scripting language
•A scripting language is a lightweight programming language
•JavaScript is usually embedded directly into HTML pages
•JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
•Everyone can use JavaScript without purchasing a license

Are Java and JavaScript the Same?
NO!
Java and JavaScript are two completely different languages in both concept and design!
Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.
What can a JavaScript Do?
JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages
JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element
JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing
JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser
JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer.

How to Put a JavaScript Into an HTML Page

<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>

To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the type attribute to define the scripting language.
So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and ends:

Where to Put the JavaScript
JavaScripts in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.
Scripts in the head section: Scripts to be executed when they are called, or when an event is triggered, go in the head section. When you place a script in the head section, you will ensure that the script is loaded before anyone uses it.

<html>
<head>
<script type="text/javascript">
....
</script>
</head>
Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a script in the body section it generates the content of the page.

<html>
<head>
</head>
<body>
<script type="text/javascript">
....
</script>
</body>

Scripts in both the body and the head section: You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section.

<html>
<head>
<script type="text/javascript">
....
</script>
</head>
<body>
<script type="text/javascript">
....
</script>
</body>

Using an External JavaScript
Sometimes you might want to run the same JavaScript on several pages, without having to write the same script on every page.
To simplify this, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension.
Note: The external script cannot contain the <script> tag!
To use the external script, point to the .js file in the "src" attribute of the <script> tag:

<html>
<head>
<script src="xxx.js"></script>
</head>
<body>
</body>
</html>

JavaScript is Case Sensitive
Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely when you write JavaScript statements, create or call variables, objects and functions.
JavaScript Statements
A JavaScript statement is a command to the browser. The purpose of the command is to tell the browser what to do.
This JavaScript statement tells the browser to write "Hello Dolly" to the web page:
document.write("Hello Dolly");
It is normal to add a semicolon at the end of each executable statement. Most people think this is a good programming practice, and most often you will see this in JavaScript examples on the web.
The semicolon is optional (according to the JavaScript standard), and the browser is supposed to interpret the end of the line as the end of the statement. Because of this you will often see examples without the semicolon at the end.
Note: Using semicolons makes it possible to write multiple 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 write a header and two paragraphs to a web page:
<script type="text/javascript">
document.write("<h1>This is a header</h1>");
document.write("<p>This is a paragraph</p>");
document.write("<p>This is another paragraph</p>");
</script>

JavaScript Comments
Comments can be added to explain the JavaScript, or to make it more readable.
Single line comments start with //.
This example uses single line comments to explain the code:
<script type="text/javascript">
// This will write a header:
document.write("<h1>This is a header</h1>");
// This will write two paragraphs:
document.write("<p>This is a paragraph</p>");
document.write("<p>This is another paragraph</p>");
</script>
JavaScript Multi-Line Comments
Multi line comments start with /* and end with */.
This example uses a multi line comment to explain the code:
<script type="text/javascript">
/*
The code below will write
one header and two paragraphs
*/
document.write("<h1>This is a header</h1>");
document.write("<p>This is a paragraph</p>");
document.write("<p>This is another paragraph</p>");
</script>

JavaScript Variables
As with algebra, JavaScript variables are used to hold values or expressions.
A variable can have a short name, like x, or a more descriptive name, like carname.
Rules for JavaScript variable names:
Variable names are case sensitive (y and Y are two different variables)
Variable names must begin with a letter or the underscore character
Note: Because JavaScript is case-sensitive, variable names are case-sensitive.
Declaring (Creating) JavaScript Variables
Creating variables in JavaScript is most often referred to as "declaring" variables.
You can declare JavaScript variables with the var statement:
var x;
var carname;

After the declaration shown above, the variables are empty (they have no values yet).
However, you can also assign values to the variables when you declare them:
var x=5;
var carname="Volvo";
After the execution of the statements above, the variable x will hold the value 5, and carname will hold the value Volvo.
Note: When you assign a text value to a variable, use quotes around the value.
Assigning Values to Undeclared JavaScript Variables
If you assign values to variables that have not yet been declared, the variables will automatically be declared.

x=5;
carname="Volvo";

JavaScript Arithmetic
As with algebra, you can do arithmetic operations with JavaScript variables:
y=x-5;
z=y+5;

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
+ Addition                 x=y+2 x=7
- Subtraction               x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division                   x=y/2 x=2.5
% Modulus  x=y%2 x=1
++ Increment x=++y x=6
-- Decrement                x=--y x=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

Adding Strings and Numbers
x=5+5;
document.write(x);

x="5"+"5";
document.write(x);

x=5+"5";
document.write(x);

x="5"+5;
document.write(x);

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                                      Example
== is equal to                                                 x==8 is false
=== is exactly equal to (value and type) x===5 is true x==="5" is false
!= is not equal                                                x!=8 is true
> is greater than                                             x>8 is false
< is less than                                                  x<8 is true
>= is greater than or equal to                          x>=8 is false
<= is less than or equal to                               x<=8 is true

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.
variablename=(condition)?value1:value2

greeting=(visitor=="PRES")?"Dear President ":"Dear ";

Conditional Statements
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
if statement - use this statement if you want to execute some code only if a specified condition is true
if...else statement - use this statement if you want 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 if you want to select one of many blocks of code to be executed
switch statement - use this statement if you want to select one of many blocks of code to be executed
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();

if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>


if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{
document.write("<b>Hello World!</b>");
}
</script>

The JavaScript Switch Statement
You should use the switch statement if you want to select one of many blocks of code to be executed.

<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
  document.write("Finally Friday");
  break;
case 6:
  document.write("Super Saturday");
  break;
case 0:
  document.write("Sleepy Sunday");
  break;
default:
  document.write("I'm looking forward to this weekend!");
}

</script>
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");

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

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

JavaScript Functions
To keep the browser from executing a script when the page loads, you can put your script into a function.
A function contains code that will be executed by an event or by a call to that function.
You may call a function from anywhere within the page (or even from other pages if the function is embedded in an external .js file).
Functions can be defined both in the <head> and in the <body> section of a document. However, to assure that the function is read/loaded by the browser before it is called, it could be wise to put it in the <head> section.

<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>

The return Statement
The return statement is used to specify the value that is returned from the function.
So, functions that are going to return a value must use the return statement.
function prod(a,b)
{
x=a*b;
return x;
}

JavaScript Loops
Very often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
In JavaScript there are two different kind of loops:
for - loops through a block of code a specified number of times
while - loops through a block of code while a specified condition is true
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

The while loop
The while loop is used when you want the loop to execute and continue executing while the specified condition is true.
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>

The do...while Loop
The do...while loop is a variant of the while loop. This loop will always execute a block of code ONCE, and then it will repeat the loop as long as the specified condition is true. This loop will always be executed at least once, even if the condition is false, because the code is executed before the condition is tested.
<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
while (i<0);
</script>
</body>
</html>

JavaScript break and continue Statements
There are two special statements that can be used inside loops: break and continue.
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

Continue
The continue command will break the current loop and continue with the next value.
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

JavaScript For...In Statement
The for...in statement is used to loop (iterate) through the elements of an array or through the properties of an object.
The code in the body of the for ... in loop is executed once for each element/property.

<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>
Events
By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript.
Every element on a web page has certain events which can trigger JavaScript functions. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags.
Examples of events:
A mouse click
A web page or an image loading
Mousing over a hot spot on the web page
Selecting an input box in an HTML form
Submitting an HTML form
A keystroke
Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs!

onload and onUnload
The onload and onUnload events are triggered when the user enters or leaves the page.
The onload event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.
Both the onload and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!".

onFocus, onBlur and onChange
The onFocus, onBlur and onChange events are often used in combination with validation of form fields.
Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field:
<input type="text" size="30"
id="email" onchange="checkEmail()">

onSubmit
The onSubmit event is used to validate ALL form fields before submitting it.
Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled:
<form method="post" action="xxx.htm"
onsubmit="return checkForm()">

onMouseOver and onMouseOut
onMouseOver and onMouseOut are often used to create "animated" buttons.
Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is detected:
<a href="http://www.w3schools.com"
onmouseover="alert('An onMouseOver event');return false">
<img src="w3schools.gif" width="100" height="30">
</a>

JavaScript Special Characters
Code Outputs
\' single quote
\" double quote
\& ampersand
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
Object Oriented Programming
JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types.
However, creating your own objects will be explained later, in the Advanced JavaScript section. We will start by looking at the built-in JavaScript objects, and how they are used. The next pages will explain each built-in JavaScript object in detail.
Note that an object is just a special kind of data. An object has properties and methods.
Properties
Properties are the values associated with an object.
In the following example we are using the length property of the String object to return the number of characters in a string:
<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>
Methods
Methods are the actions that can be performed on objects.
In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters:
<script type="text/javascript">
var str="Hello world!";
document.write(str.toUpperCase());
</script>

var myDate=new Date()

var myDate=new Date();
myDate.setFullYear(2010,0,14);


var myDate=new Date();
myDate.setDate(myDate.getDate()+5);

var myDate=new Date();
myDate.setFullYear(2010,0,14);
var today = new Date();
if (myDate>today)
{
alert("Today is before 14th January 2010");
}
else
{
alert("Today is after 14th January 2010");
}

Create an Array
The following code creates an Array object called myCars:
var myCars=new Array()
There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).
var myCars=new Array();
mycars[0]="Saab";
mycars[1]="Volvo";
mycars[2]="BMW";
You could also pass an integer argument to control the array's size:
var myCars=new Array(3);
mycars[0]="Saab";
mycars[1]="Volvo";
mycars[2]="BMW";

var myCars=new Array("Saab","Volvo","BMW");

document.write(myCars[0]);

myCars[0]="Opel";

document.write(myCars[0]);

JavaScript String Object

Methods Explanation
length Returns the number of characters in a string
indexOf() Returns the index of the first time the specified character occurs, or -1 if it never occurs, so with that index you can determine if the string contains the specified character.
lastIndexOf() Same as indexOf, only it starts from the right and moves left.
match() Behaves similar to indexOf and lastIndexOf, but the match method returns the specified characters, or "null", instead of a numeric value.
substr() Returns the characters you specified: (14,7) returns 7 characters, from the 14th character.
substring() Returns the characters you specified: (7,14) returns all characters between the 7th and the 14th.
toLowerCase() Converts a string to lower case
toUpperCase() Converts a string to upper case

Eg:

1.

<html>
<body>
<script type="text/javascript">
var str="Web Enabling Tools is Cool!"
document.write("<p>" + str + "</p>")
document.write("str.length")
</script>
</body>
</html>

2.

<html>
<body>
<script type="text/javascript">
var str="Web Enabling Tools is Cool!"
var pos=str.IndexOf("Enabling")
if (pos>=0)
{
document.write("School found at position: ")
document.write(pos + "<br>")
} else {
document.write("Enabling not found!")
}
<p>This example tests if a string contains a specified word. If the word is found it returns the position of the first character of the word in the original string. Note: The first position in the string is 0!
</script>
</body>
</html>

<html>
<head>
<title>
IC
</title>
<script>
function mnic(icno)
{
var mm,yy,dd, msex;
var mymon = new Array();
mymon[0]=31;
mymon[1]=29;
mymon[2]=31;
mymon[3]=30;
mymon[4]=31;
mymon[5]=30;
mymon[6]=31;
mymon[7]=31;
mymon[8]=30;
mymon[9]=31;
mymon[10]=30;
mymon[11]=31;


yy=icno.substr(0,2);

dd=parseInt(icno.substr(2,3));
if (dd >= 500)
{
msex="Female";
dd = dd - 500;
}
else
{
msex="Male";
}
document.write("You are a :" + msex);
document.write("Your Birth Year :"  + yy);
document.write("<br>");
mm=0;
while (dd > mymon[mm])
{
dd=dd - mymon[mm];
mm=mm+1;
}
document.write("Your Birth Month :" + (mm +1));
document.write("<br>");
document.write("Your Birth day :" + dd);
document.write("<br>");

}

</script>
</head>
<body>
<form name="mf">
Enter Your NIC No :
<input name="mic" type="text">
<br>
<input name="mbut" type="button" onclick="mnic(mf.mic.value)" value="Click Here">
</form>
</body>
</html>


DHTML
DHTML is Not a Language

DHTML stands for Dynamic HTML.

DHTML is NOT a language or a web standard.

DHTML is a TERM used to describe the technologies used to make web pages dynamic and interactive.

To most people DHTML means the combination of HTML, JavaScript, DOM, and CSS.

JavaScript and the HTML DOM
With HTML 4, JavaScript can also be used to change the inner content and attributes of HTML elements dynamically.

To change the content of an HTML element use:
document.getElementById(id).innerHTML=new HTML

To change the attribute of an HTML element use:
document.getElementById(id).attribute=new value

JavaScript and CSS
With HTML 4, JavaScript can also be used to change the style of HTML elements.
To change the style of an HTML element use:
document.getElementById(id).style.property=new style

Eg :1
<html>
<head>
<script type="text/javascript">
function newh()
{
document.getElementById("header1").innerHTML="New header";
document.getElementById("header1").style.color="red";
}
function oldh()
{
document.getElementById("header1").innerHTML="old header";
document.getElementById("header1").style.color="blue";
}
</script>
</head>
<body>
<h1 id="header1"> hi how r u </h1>
<br>
<input type="button" name="mbut1" value="new" onclick="newh()">
<br>
<input type="button" name="mbut2" value="old" onclick="oldh()">
</script>
</body>
</html>

Eg :2
<html>
<body>
<h1 onmouseover="style.color='pink'" onmouseout="style.color='blue'">
mouse over this text </h1>
</body>
</html>

Eg : 3
<html>
<body>
<img id="image" src="smiley.gif">
<script type="text/javascript">
document.getElementById("image").src="landscape.jpg";
</script>
</body>
</html>
Eg : 4
<html>
<head>
<script type="text/javascript">
cc=0;
function changeimage()
{
if (cc==0)
{
cc=1;
document.getElementById('myimage').src="bulbon.gif";
}
else
{
cc=0;
document.getElementById('myimage').src="bulboff.gif";
}
}
</script>
</head>
<body>
<img id="myimage" onclick="changeimage()"
border="0" src="bulboff.gif"
width="100" height="180" />
<p>Click to turn on/off the light</p>
</body>
</html>

Eg :5
<html>
<head>
<script type="text/javascript">
function changetext(id)
{
id.innerHTML="Ooops!";
}
</script>
</head>
<body>
<h1 onclick="changetext(this)">Click on this text</h1>
</body>
</html>

Eg: 6

<html>
<head>
<script type="text/javascript">
function blinking_header()
{
if (!document.getElementById('blink').style.color)
{
document.getElementById('blink').style.color="red";
}
if (document.getElementById('blink').style.color=="red")
{
document.getElementById('blink').style.color="black";
}
else
{
document.getElementById('blink').style.color="red";
}
timer=setTimeout("blinking_header()",500);
}

function stoptimer()
{
clearTimeout(timer);
}
</script>
</head>

<body onload="blinking_header()" onunload="stoptimer()">
<h1 id="blink">Blinking header</h1>
</body>
</html>

Event Handlers

Event Occurs when...
onabort a user aborts page loading
onblur a user leaves an object
onchange a user changes the value of an object
onclick a user clicks on an object
ondblclick a user double-clicks on an object
onfocus a user makes an object active
onkeydown a keyboard key is on its way down
onkeypress a keyboard key is pressed
onkeyup a keyboard key is released
onload a page is finished loading
onmousedown a user presses a mouse-button
onmousemove a cursor moves on an object
onmouseover a cursor moves over an object
onmouseout a cursor moves off an object
onmouseup a user releases a mouse-button
onreset a user resets a form
onselect a user selects content on a page
onsubmit a user submits a form
onunload a user closes a page





No comments:

Post a Comment