Vous êtes sur la page 1sur 57

Java Script

Introduction to Java Script


Java is a full programming language developed by Sun Microsystems with formal structures. JavaScript is a scripting language developed by Netscape that is used to modify web pages. JavaScript written in the HTML document between <SCRIPT> tags. An optional attribute to script, Language=JavaScript can be added JavaScript is object-oriented. document, is an object which represents the current page has properties such as location methods such as writeln , Used to write dynamically created html text to the document.

Features of JavaScript
Programming Tool for interactive HTML pages Interpreted Language Saves time as validation is done on Client side Event-Driven Programming Detects Client browser, hence platform independent

Scripts vs. programs


A scripting language is a simple, interpreted programming language scripts are embedded as plain text, interpreted by application simpler execution model: don't need compiler or development environment saves bandwidth: source code is downloaded, not compiled executable platform-independence: code interpreted by any scriptenabled browser but: slower than compiled code, not as powerful/full-featured

Common scripting tasks


adding dynamic features to Web pages
validation of form data image rollovers time-sensitive or random page elements handling cookies

defining programs with Web interfaces


utilize buttons, text boxes, clickable images, prompts, frames

limitations of client-side scripting


since script code is embedded in the page, viewable to the world for security reasons, scripts are limited in what they can do can't access the client's hard drive since designed to run on any machine platform, scripts do not contain platform specific commands

Where to put Java script


JavaScripts are executed when: A web page loads into the browser. An event is triggered. Depending on the above two conditions, JavaScript will be included in the body section or in the head section of the HTML file.

Script Execution Head Section


Scripts, placed in the head section will be executed When they are called or When an event is triggered.
html> <head> <script language=javascript"> some statements </script> </head> </html> Advantage The script will be loaded before anyone uses it.

Scripts Execution - Body Section


A script to be executed while the page is being loaded is placed in the body section.

<html> <head> </head> <body> <script type=javascript"> some statements </script> </body> </html>

Advantage The script generates the content of the page.

What is a Variable?
Information is stored in variables. Its value can be change during the execution of script. It can be referenced by its name to see its value or to change its value.

Datatype supported Variant.


Variant can store any type of data.

Declaring Variables
There are two ways of declaring a variable. Implicit Declaration Explicit Declaration Implicit Declaration Declare variables by using its name directly in the script. For example : name=Tom Explicit declaration - Using var keyword For example : var name name=Tom

JavaScript data types & variables


JavaScript has only three primitive data types
strings Numbers Booleans

variable names are sequences of letters, digits, and underscores: start with a letter variables names are case-sensitive don't have to declare variables, will be created the first time used
var x= hello; var x=1;

Variant
Integer Float

Boolean

Char

Variant

Writing HTML to The Document


<html> <head> <title>JavaScript Page</title> </head> <body> <script type="text/javascript"> document.write("Hello world!"); document.write("<p>How are <br />" + "<i>you</i>?</p>"); </script> <p>Here is some static text as well.</p> </body> </html>

JavaScript data types & variables


<html> <head> <title>Data Types and Variables</title> </head> <body> <script type="text/javascript"> x = 1024; document.write("<p>x = " + x + "</p>"); x = Hello"; document.write("<p>x = " + x + "</p>"); </script> </body> </html>

User-defined functions
User Defined Functions
no return type for the function (since variables are loosely typed) no types for parameters (since variables are loosely typed) by-value parameter passing only (parameter gets copy of argument

Variable scope is limited if the first use of a variable is preceded with var, then that variable is local to the function Function definitions go in the HEAD HEAD is loaded first, so the function is defined before code in the BODY is executed

Using Arrays
<script type="text/javascript"> function show() { var names = new Array("Ramesh","Suresh","Ganesh); for(i =0;i<3;i++) { document.writeln(names[i]); } } </script> <body> <script language="JavaScript"> show(); </script> </body>

document object
Both IE and Netscape allow you to access information about an HTML document using the document object (Note: not a class!) document.write()
method that displays text in the page

document.URL
property that gives the location of the HTML document

document.lastModified
property that gives the date & time the HTML document was saved <script language= JavaScript> <!-document.writeln(<p><br> This page is located at +document.location+ <br>This page was last modified on +document.lastModified); //--> </script>

Calling Java Script From .js Files


Creating a Separate Java Script File
function display { document.writeln("Hello From Java Script"); }

Create a HTML File to invoke the same <script language="javascript" src="First.js"></script> <FORM > <INPUT TYPE="BUTTON" NAME="b1" VALUE="What\'s your name" onClick=display()"> </FORM>

In lining of JavaScript
<html> <head> <title>Example</title> </head> <body>

<input type="button" value="Click" onclick="javascript:alert('Wrong Button Clicked')"/> </body> </html>

Alert boxes
An alert box is a small window that pops up with a yellow warning sign and a (usually) important message. With JavaScript we can either show a message to the user either before a page loads or in response to a user action.

<script LANGUAGE=JavaScript>
alert (Welcome to the Test Site!); </script>

Confirm Boxes
Confirm box User will have to click either "OK" or "Cancel" to proceed
<form> <input type = ''button" value = "Click here to check the weather" onClick = "confirm(Itssunny today ' ) ; " > </form>

The onClick event handler means that when click on the button, a confirm box pops up.

Message input boxes


Prompt box User will have to click either "OK" or "Cancel" to proceed after entering an input value prompt("sometext","defaultvalue")

<script language= JavaScript>


<! var yourname = prompt('Type your name here'); document.writeln("<center>Welcome, "+ yourname+"</center>"); //--> </script>

Java Script Events


Every element on a web page has certain events which can trigger invocation of event handlers Attributes are inserted into HTML tags to define events and event handlers 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

Some More Event


onblur onchange onclick ondblclick onfocus onkeydown onselect onsubmit onunload - An element loses focus - The content of a field changes - Mouse clicks an object - Mouse double-clicks an object - An element gets focus - A keyboard key is pressed - Text is selected - The submit button is clicked - The user exits the page

Onload & onUnload Events


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.

onload & onUnload Events


<SCRIPT LANGUAGE="JavaScript"> <! function Hello() { alert("Welcome to My Page"); } function Goodbye(){ alert("Thank you for visiting. Come again soon!"); } //--> </SCRIPT> <body onLoad="Hello()" onUnLoad="Goodbye()">

onLoad
<html> <head> <title>A Simple Page</title> <script language="JavaScript"> <!-function yourMessage() { alert("Your first function!"); } // --> </script> </head> <body onLoad="yourMessage()"> </body> </html>

onFocus, onBlur and onChange


The onFocus, onBlur and onChange events are often used in combination with validation of form fields.

Example: The checkEmail() function will be called whenever the user changes the content of the field:

<input type="text" size="30 id="email" onchange="checkEmail()">;

Example : onblur
<html> <head> <script type="text/javascript"> function upperCase() { var x=document.getElementById("fname").value document.getElementById("fname").value=x.toUpperCase() } </script> </head> <body> Enter your name: <input type="text" id="fname" onblur="upperCase()"> </body>

onSubmit
The onSubmit event is used to validate ALL form fields before submitting it.

Example: 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.html" onsubmit="return checkForm()">

onSubmit
When calling functions parameters are sent by including them in the parentheses that follow the function name. The this statement passes a reference to the form object associated with the current form.

The return statement transmits a value back to the internal routine that called the onsubmit event handler.

Example & Demo: onSubmit


<html> <head> <script type="text/javascript"> function validate() { // return true or false based on validation logic } </script> </head> <body> <form action= " onsubmit="return validate()"> Name (max 10 chararcters): <input type="text" id="fname" size="20"><br /> Age (from 1 to 100): <input type="text" id="age" size="20"><br /> E-mail: <input type="text" id="email" size="20"><br /> <br /> <input type="submit" value="Submit"> </form> </body> </html>

OnSubmit
<script language="JavaScript"> function sendMe() { return confirm("Do you want to continue the submission?"); } </script> </head> <body> <form name="form1" method="POST" action="" onSubmit="return sendMe()"> <P><input type="text" name="inp1"> <input type="submit" value="Submit" > <input type="reset" value="Reset"></p> </form>

The Mouse Over


A mouseover can be used to make an image change when the user rolls their mouse over it.

The browser displays a different image when the mouse is over the text or image.
To specify a mouse rollover the onMouseOver or the onMouseOut attributes into the appropriate tag.

The Mouse Over


<a href="First.html"

onmouseover="document.pict.src ='images/B.GIF'"
onmouseout="document.pict.src='images/A.GIF'">

<img name="pict" alt="An Image" src="images/A.GIF">


</a>

OnMouseDown
<html> <head> <script type="text/javascript"> function show_coords(event) { x=event.clientX y=event.clientY alert("X coords: " + x + ", Y coords: " + y) } </script> </head> <body onmousedown="show_coords(event)"> <p>Click in the document. An alert box will alert the x and y coordinates of the cursor.</p> </body> </html>

Custom Submit Button


<html> <head> <title>Submit Example</title> </head> <body> <form id="form1" method="post" action="javascript:alert('Submitted')"> /><br /> <input type="text" id="txtName" name="txtName"

<!-- custom submit button --> <input type="button" value="Submit Form" onclick="document.forms[0].submit()" />
</form> </body> </html>

Opening Linked Windows with JavaScript


<script type="text/javascript" language="javascript"> function popup(url) { mywindow = window.open(url, 'name', 'height=200,width=400'); return false; } </script> </head> <body> <h1>Popup Example</h1> <p><a href="popup.html" onclick="popup('popup.html')">Launch popup</a> </p> </body> </html>

Validate Form Fields


<script> <!-function validate() { if (document.info.name.value=="") { alert ("Please input your name.") return false } if (document.info.address.value=="") { alert ("Please input your address.") return false } if (document.info.email.value=="") { alert ("Please input your e-mail address.") return false } } //--> </script>

Validate Form Fields


<FORM NAME="info" METHOD=POST ONSUBMIT="return validate() action="">

UserName <input type="text" name="name"/> <p> Address <input type="text" name="address"/> <p> Email : <input type="text" name="email"/> <p> <input type="submit" value="Register"/>
</form>

Java Script is an OOP


A JavaScript object has properties and methods

Example: String JavaScript object has length property and toUpperCase() method

<script type="text/javascript"> var txt="Hello World!" document.write(txt.length) document.write(txt.toUpperCase()) </script>

Java Script Object


By invoking the built-in constructor for the Object class Initially empty with no properties or methods
personObj=new Object();

Add properties to it
personObj.firstname="John"; personObj.lastname="Doe"; personObj.age=50;

Add an anonymous function to the personObj personObj.tellYourage=function(){ alert(This age is + this.age); }

JavaScript Object vs. Java Object


Similarities

Both has properties and methods


Differences JavaScript object can be dynamically typed while Java object is statically typed In JavaScript, properties and methods are dynamically added

HTML DOM Objects


Option and Select objects Screen object Table, TableHeader, TableRow, TableData objects Window object

Creating a Instance
Add a pre-defined function
function tellYourage(){ alert(The age is + this.age); } personObj.tellYourage=tellYourage;

Note that the following two lines of code are doing completely different things

personObj.tellYourage=tellYourage; personObj.tellYourage=tellYourage();

Creating a Template of the Object


The template defines the structure of a JavaScript object in the form of a function You can think of the template as a constructor function Person(firstname,lastname,age,eyecolor) {

this.firstname=firstname; this.lastname=lastname; this.age=age; this.tellYourage=function(){ alert(This age is + this.age);


Once you have the template, you can create new instances of the object

myFather=new Person("John","Doe",50,"blue"); myMother=new Person("Sally","Rally",48,"green");


You can add new properties and functions to new objects

myFather.newField = some data;

HTML DOM
The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML documents

All HTML elements, along with their containing text and attributes, can be accessed through the DOM. The contents can be modified or deleted, and new elements can be created.
The HTML DOM is platform and language independent It can be used by any programming language like Java, JavaScript, and VBScript

HTML DOM Objects


Anchor object Document object Event object Form and Form Input object Frame, Frameset, and IFrame objects Image object Location object Navigator object

Document Object: Use getElementById()


<html> <head> <script type="text/javascript"> function getElement() { var x=document.getElementById("myHeader") alert("I am a " + x.tagName + " element") } </script> </head> <body> <h1 id="myHeader" onclick="getElement()">Click to see what element I am!</h1> </body> </html>

Use getElementsByName()
<html> <head> <script type="text/javascript"> function getElements() { var x=document.getElementsByName("myInput") alert(x.length + " elements!") } </script> </head> <body> <input name="myInput" type="text" size="20"><br /> <input name="myInput" type="text" size="20"><br /> <input name="myInput" type="text" size="20"><br /> <br /> <input type="button" onclick="getElements()" value="How many elements named 'myInput'?"> </body> </html>

Return the innerHTML


<html> <body> <a name="first">First anchor</a><br /> <a name="second">Second anchor</a><br /> <a name="third">Third anchor</a><br /> <br />

InnerHTML of the first anchor in this document:


<script type="text/javascript"> document.write(document.anchors[0].innerHTML) </script> </body> </html>

Access an item in a collection


<html> <body> <form id="Form1" name="Form1"> Your name: <input type="text"> </form> <form id="Form2" name="Form2"> Your car: <input type="text"> </form> <p> To access an item in a collection you can either use the number or the name of the item: </p> <script type="text/javascript"> document.write("<p>The first form's name is: " + document.forms[0].name + "</p>") document.write("<p>The first form's name is: " + document.getElementById("Form1").name + "</p>") </script> </body> </html>

Event Object: Check the Event Type


<html> <head> <script type="text/javascript"> function whichType(event) { alert(event.type) } </script> </head> <body onmousedown="whichType(event)"> <p> Click on the document. An alert box will alert which type of event occurred. </p> </body> </html>

Cookies - Set
function set_it() { var the_text="name=yourName&"; var toexpire= new Date("March 15, 2008"); var expdate="expires="+toexpire.toGMTString(); the_text+=expdate; var newtext=escape(the_text); document.cookie=newtext; }

Cookies-Read
function read_it() { if (document.cookie) { var var var var var mycookie=document.cookie; fixed_cookie= unescape(mycookie); thepairs= fixed_cookie.split("&"); pair1= thepairs[0]; pair2= thepairs[1];

var namevalue1= pair1.split("="); alert("read"); alert("Welcome, "+namevalue1+"!"); } else { alert("set"); set_it(); } }

Javascript is a scripting language which can be used in Web pages to do client side validations. It is supported by all the browsers.

It is also used to validate web pages to improve design and add functionality to web pages.