Page 1

Introduction Java script is easy programming language specifically designed to make web page elements interactive. An interactive element is one that responds to a user's input.JavaScript is the most popular scripting language on the Internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari . JavaScript was developed by Netscape and called as “LiveScript”.Next,JavaScript was developed by Netscape and Sun Microsystems in 1995 and renamed as “JavaScript”.. Microsoft created Jscript for its Internet Explorer similar to Netscape JavaScript What is JavaScript Javascript scripts are the ideal way to add special effects and extra bits and bobs to your pages without having to resort to plug-ins or full-on applets. There are a myriad of uses for this most versatile of scripting languages. • • • • • • •

JavaScript was designed to add interactivity to HTML pages JavaScript is object-based 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) JavaScript can run on both client-side and server-side. Everyone can use JavaScript without purchasing a license

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

Difference between Java and JavaScript JavaScript is different from Java programming language, Unlike Java, which needs compilation; JavaScript is dynamic and is interpreted in run-time. Though there are some similarities like both Java and JavaScript are client-side programming language, both descend from C++ yet both Java and JavaScript differ in many ways

• Java was developed by Sun Microsystems while JavaScript was developed by Netscape.. • JavaScript is a high-level scripting language whereas Java is an Object Oriented Programming language. . • JavaScript is easy to learn and use whereas Java is comparatively difficult. . • In case of Java programming language the code is first written and then compiled. In JavaScript the script can be executed without any compilation. . • JavaScript as conveyed can be directly embedded or placed in HTML but it is not possible in case of Java. One cannot write Java code directly into HTML. . Advantages of JavaScript JavaScript offers numerous features which makes it popular. Few among them are listed below: • JavaScript is a dynamic open scripting language with simple syntax and rules which makes it easier to use and learn for programmers. This has made JavaScript a popular Client-side scripting language. •

JavaScript is an interpreted language meaning that it could be used or executed with ease without pre-compilation.

JavaScript is very useful for creating interactive web pages or web sites.

JavaScript helps in adding dynamic functionality to websites

JavaScript makes it very easier to validate a form at the client side without connecting to server. JavaScript has the ability to instantly notify users in case there is any mistake in input data.

Writing JavaScript JavaScript code is typically embedded in the HTML, to be interpreted and run by the client's browser. Here are some tips to remember when writing JavaScript commands.

JavaScript code is case sensitive

White space between words and tabs are ignored

Line breaks are ignored except within a statement

JavaScript statements end with a semi- colon ;

Syntax: <SCRIPT language = "JavaScript"> statements </SCRIPT> <SCRIPT> Tag: •

The script tag has two purposes:

1. It identifies a block of script in the page. 2. It loads a script file.

The <script> tag is used to define a client-side script, such as a JavaScript.

The script element either contains scripting statements or it points to an external script file through the src attribute.

The <script> tag has several attributes, two of which you should always set: language and type.

<script> tag attributes: Attribute





Specifies the MIME type of a script



Specifies the URL of an external script file



Specifies the language of a script. It was used to select other programming languages and specific versions of JavaScript.

Integrating JavaScript into Your Web Documents: There • • • • •

are basically five ways to place JavaScript in HTML file: In a <script> tag in the head of an HTML document In a <script> tag in the body of an HTML document. Inline with HTML as an event handler. In an external JavaScript file. Inline using the javascript pseudo-protocol.

Placing JavaScript Statements in a <script> Tag within the <head>: <html> <head> <title>Placing JavaScript Statements Appropriately</title> <script language="JavaScript" type="text/javascript"> <!-var visitor = prompt("What is your name?", "") // --> </script> </head> <body> </body> </html>


Placing JavaScript Statements in a <script> Tag within the <body>: <html> <head> <title>Placing JavaScript Statements Appropriately</title> <script language="JavaScript" type="text/javascript"> <!-var visitor = prompt("What is your name?", "") // --> </script> </head> <body> <script language="JavaScript" type="text/javascript"> <!-document.write("<h1>Welcome, ", visitor, "</h1>") </body> </html>

Placing JavaScript Statements Inline as Event Handlers: <html> <head><title>Writing JavaScript Inline with HTML</title></head> <body onLoad="alert('Welcome!')"> </body> </html>


Placing JavaScript Statements in an External JavaScript file: <html> <head> <title>Placing JavaScript Statements Appropriately</title> <script language="JavaScript" src=”ExternalJavaScriptFile.js”></script> </head> <body onLoad=”welcomeMsg()”> </body> </html>

ExternalJavaScriptFile.js: function welcomeMsg() { alert("Welcome"); }


Placing JavaScript Statements Inline using the JavaScript Pseudo-Protocol: We can also write JavaScript statements using the javascript: pseudo-protocol in the href attribute of an anchor (<a></a>) or area (<area>) tag. The idea is that instead of going right to a document or resource, the JavaScript pseudo-protocol will instead execute one or more JavaScript statements, which may or may not return a URL for the anchor tag to follow.

<html> <head> <title>Writing JavaScript statements Inline using the JavaScript Pseudo-protocol</title> </head> <body> <a href=”javascript:alert(“welcome”)”>Welcome Message</a> </body> </html>


Javascript operators: JavaScript operators are used to perform an operation. There are different types of operators for different uses. Arithmetic Operators:



+ JavaScript Variables: Like other programming languages, JavaScript variables are a container that contains a value - a value that can be changed as required. Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. we can place data into these containers and then refer to the data simply by naming the container. Declaring JavaScript Variables: we declare variables in JavaScript with the var keyword. we can declare multiple variables at once. we can also declare a variable and assign it a value at the same time. Until we assign a value to a variable it is undefined. If we try to declare a variable that already exists, JavaScript will treat it as a simple assignment statement and assign any new value in the declaration statement to the variable. If the duplicate declaration has no assignment, then nothing happens. If we try to assign a value to a non-existent variable, JavaScript will create the variable for us. Here is some code creating and assigning values to a couple of variables: <html> <head> <title>Declaring javascript variables</title> </head> <body> <script language="JavaScript" type="text/javascript"> var username=”user@cnb”; <!-document.write("<h1>Welcome, ", username, "</h1>") </body> </html>

Variable Naming Conventions: While naming your variables in JavaScript keep following rules in mind. • JavaScript variables must start with a letter or underscore "_". JavaScript variable names

should not start with a numeral (0-9). • •

JavaScript is case sensitive. should not use any of the JavaScript reserved keyword as variable name.

Variable Scope and Lifetime: •

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes. ◦ Global Variables: A global variable has global scope which means it is defined everywhere in your JavaScript code. ◦ Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function. The lifetime of Global variables starts when they are declared, and ends when the page is closed.

Example: <script type="text/javascript"> var altitude = 5; //GLOBAL function square( ) { base = 17; //GLOBAL sqr = 0.5*(base + altitude); return sqr; } function perimeter(){ var side = 7.5; //LOCAL prm = 2*side + base; return prm; } </script>

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 the function.

You may call a function from anywhere within a 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 a function is read/loaded by the browser before it is called, it could be wise to put functions in the <head> section.

The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.

Syntax: function function-name(var1,var2,...,varX) { some code } Example: <html> <head> <script type="text/javascript"> function displaymessage() { alert("Hello World!"); } </script> </head> <body> <form> <input type="button" value="Click Here!" onclick="displaymessage()" /> </form> </body> </html> Output:

JavaScript Events:

Events are actions that can be detected by JavaScript.JavaScript's interaction with HTML is handled through events that occur when the user or browser manipulates a page. Every element on a web page has certain events which can trigger a JavaScript.

Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable to occur.

Events are a part of the Document Object Model (DOM) Level 3.

Here we will see few examples to understand a relation between Event and JavaScript: 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!"

Example: <html>

<body onload="alert('This page has starting loading!')" onUnload="alert('This page has finished loading!')"> </body> </html>


onFocus: • •

The onFocus event occurs when an object gets focus. The JavaScript onFocus event handler is used to trigger a script or action when an element gains focus either by a mouse clicking on it, by a script or by a tabbing order. The onFocus event calls the action from the following elements: • <a> • <area> • <button>

• • • •

<input> <label> <select> <textarea>

Example: <html> <head> <script type="text/javascript"> function setStyle(x) { document.getElementById(x).style.background="gray" } </script> </head> <body> <br/> First name: &nbsp;&nbsp;&nbsp;<input type="text" onfocus="setStyle(" id="fname"> <br /> Last name: &nbsp;&nbsp;&nbsp;<input type="text" onfocus="setStyle(" id="lname"> </body> </html>

Output: Before Event:

After Event:

onMouseOver and onMouseOut: The onmouseover event occurs when you bring your mouse over any element and the onmouseout occurs when you take your mouse out from that element.

Example: <html> <head> <script type="text/javascript"> <!-function over() { alert("Mouse Over"); } function out() { alert("Mouse Out"); } //--> </script> </head> <body> <div onmouseover="over()" onmouseout="out()"> <h2> Testing the onmouseover and onmouseout events </h2> </div> </body> </html>

Output: Testing the onmouseover and onmouseout events when onmouseover:

when onmouseout:

onClick: The JavaScript onclick event handler is used to trigger a script or action when a user clicks a mouse or a pointing device on an element. The onclick event calls the action from most elements. Example: <html> <head> <script type="text/javascript"> <!-function test() { alert("Testing Javascript Events") } //--> </script> </head> <body> <input type="button" onclick="test()" value="Test OnClick Event" /> </body> </html>


onSubmit: The JavaScript onsubmit event handler is used to trigger a script or action when a form is submitted that is when the submit button is depressed. The onsubmit event calls the action from the <form> element. Example: <html> <head> </head> <body> <form action="#" method="post" onsubmit="alert('You are submitting a form now');"> <input type="text" ><br> <input type="submit" value="submit" > </form> </body> </html>


ondblclick: The JavaScript ondblclick event handler is used to trigger a script or action when a user double-clicks a mouse or a pointing device on an element. The ondblclick event calls the action from most elements. Example: <html> <body bottommargin=150 ondblclick="alert('double clicked!')"> <p>Double-click anywhere in the page.</p> </body> </body> </html>

Output: Double-click anywhere in the page

onselect: The JavaScript onselect event handler is used to trigger a script or action when a user selects some text in a text field. The onselect event calls the action from the <input> or <textarea> element.

Example: <html> <head> <script type=”text/javascript”> function test() { alert(“You have selected some text”); } </script> <body> <form action="#" method="post" > <textarea onselect="test();"></textarea></br> <input type="submit" value="submit" > </form> </body> </html>

JavaScript Cookies: •

A cookie is simply a variable that your webpage can store on or retrieve from the user's computer.

A cookie is a small text file that is stored on the site visitor's computer by their browser.

Cookies were originally designed for CGI programming and cookies' data is automatically transmitted between the web browser and web server, so CGI scripts on the server can read and write cookie values that are stored on the client.

JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookie or cookies that apply to the current web page.

The JavaScript cookie is a document object. Cookies are a plain text data record of 5 variable-length fields: • Name=Value : Cookies are set and retrieved in the form of key and value pairs. • Expires : The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser. • Domain : The domain name of your site. • Path : The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page. • Secure : If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.

Cookie Path: Cookies are, by default, available to all other files in the same directory the cookie was created in. To make a cookie available to all files on the webserver use the path statement similar to: document.cookie = "javahere=yes; path=/"; To make the cookie available to the javascript directory and all its subdirectories only use a statement like: document.cookie = "javahere=yes; path=/javascript"; Cookies may have the same name with different values. Domain: The "domain" parameter is used to set the domain the cookie is accessible to. A path can be set for your own domain only and the domain path must include at least two periods ( It must match your server's domain name. Therefore cookies are not a security risk since only the server that sets them can use them. Secure: If the "secure" parameter is set, the cookie can only be sent to a Secure Sockets Layer (SSL) server which would have a URL like: It uses "HTTPS" for the protocol rather than "HTTP".

Storing Cookies: The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this: Syntax: document.cookie = "key1=value1;key2=value2;expires=date";

Here expires attribute is option. If you provide this attribute with a valid date or time then cookie will expire at the given date or time and after that cookies' value will not be accessible. Reading Cookies: Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value. You can use strings' split() function to break the string into key and values. Setting the Cookies Expiration Date: You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiration date within the cookie. This can be done by setting the expires attribute to a date and time. Deleting a cookie: Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiration date to a time in the past. Creating Cookies in JavaScript: Create or set a cookie on user machine having cookie name, cookie value and the time.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; }

JavaScript Objects:

• • •

JavaScript objects come from web documents and are made available to client-side javascript via the Document Object Model (DOM) - Math, String, Date, and Array. A few objects come from the browser - navigator, location, and history. Programmer can create own custom objects.

Document Object Model : •

The Document Object Model is a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents. The document can be further processed and the results of that processing can be incorporated back into the presented page.

The Document Object Model (DOM) is a standardized software interface that allows code written in JavaScript and other languages to interact with the contents of an HTML document. The Document Object Model consists of a series of classes that represent HTML elements, events, and so on, each of which contains methods that operate on those elements or events

The foundation of Extensible Markup Language, or XML, is the DOM. XML documents have a hierarchy of informational units called nodes; DOM is a way of describing those nodes and the relationships between them. The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines a standard for accessing documents like XML and HTML.

The DOM defines the objects and properties of all document elements, and the methods (interface) to access them.

While JavaScript is the programming language which will allow you to operate on the DOM objects and to manipulate them programmatically, the DOM will provide you with methods and properties to retrieve, modify, update, and delete parts of the document you are working on.

The DOM is separated into 3 different parts / levels: • Core DOM - standard model for any structured document • XML DOM - standard model for XML documents • HTML DOM - standard model for HTML documents

The Document Object Model (DOM) is a tree structure representing an HTML page.Let’s review a sample of HTML code and it’s corresponding DOM tree.

Sample HTML code: <<div id="sample"> This is a <b>sample of HTML</b> <br> to demonstrate the DOM </div>

Here is the corresponding DOM structure:

How To Access Document Object Model (DOM) using JavaScript:

• • •

DOM represents the contents of a webpage as a “tree” of javascript objects. By

accessing the parts of the tree, called the nodes, we can read existing page content, alter content, and even add new content from scratch. We can locate and retrieve the elements of a web page using JavaScript and DOM. DOM tree is completely comprised of Javascript objects.By using those objects we can access content of web page. • JavaScript DOM objects: • document • element • nodeList Various ways to access contents of a webpage are as follows: • Finding elements by ID • Finding elements by tag name • Finding elements via their name attributes • Finding elements by their relationship

Finding elements by ID: The easiest way to access an element is via its id attribute, because an element's id is unique in the page. Here's how it's done: var element = document.getElementById( elementId );

Finding elements by tag name: If elements doesn't has id then we can access elements by tag name. Here's how it's done: var element = document.getElementsByTagName( tagName );

Finding elements via their name attributes: If we have elements within web page that have name attributes – such as input fields and select menus – then we retrieve those elements via their names with document.getElementByName. Here's how it's done: var elements = document.getElementByName( name );

Finding elements via their relationship: Because each node in the DOM tree is related to every other node, once we have retrieved one node we can theoretically access any other node in the tree by hopping between the nodes. To do this, we use properties of each node such as parentNode (to retrieve the node's parent) and childNodes (to retrieve the children of the node). JavaScript DOM objects: •

Document Object:

Represents the root node of the DOM tree, and actions on it will affect the entirety of the page. The document represents the whole page, its attributes indicate how it is defined and its methods allow access to its content. It is used with the keyword document: •

Attributes of Document Object:

These are read-only • • • • • • • • • • • • •

attributes defined when creating the page. body body.offset compatMode documentMode docType documentElement domain implementation ownerDocument readyState styleSheets[] title URL

• Methods of Document Object: The DOM methods can take for parameter a DOMString object, which in practice is a simple string in JavaScript. • GetElementById • getElementsByTagName • getElememtByName • getSelection • captureEvents • handleEvent • releaseEvent • routeEvent • write • writeIn

• •

open close

GetElementById(): If you want to quickly access the value of an HTML input give it an id to make your life a lot easier. This small script below will check to see if there is any text in the text field "myText". The argument that getElementById requires is the id of the HTML element you wish to utilize. Example:

<script type="text/javascript"> function notEmpty(){ var myTextField = document.getElementById('myText'); if(myTextField.value != "") alert("You entered: " + myTextField.value) else alert("Would you please enter some text?") } </script> <input type='text' id='myText' /> <input type='button' onclick='notEmpty()' value='Form Checker' /> Output:


getElementsByName(): The getElementById method was used for returning the reference to the first object with the specified ID. The programmer can also get a collection of objects with the object name given in argument by using the method getElementsByName. The getElementsByName() method returns a collection of objects with the specified Name given in argument. This method returns an array of elements with a name attribute whose value matches that of the parameter given. Example:

<html> <head> <script type="text/javascript"> function Exforinput() { var test=document.getElementsByName("Exforsys"); alert(test.length); } </script> </head> <body> <input name="Exforsys" type="text" size="30" /><br /> <input name="Exforsys" type="text" size="30" /><br /> <input type="button" onclick="Exforinput()" vkalue="Click to see the number of input box" /> </body> </html> Output:


getElementsByTagName(): The the getElementsTagName() method returns a collection of objects with the specified TagNAME given in argument. The programmer can enter an asterisk ("*") as the parameter to retrieve a list of all elements within the document. Example:

<html> <head> <script type="text/javascript"> function Exforinput() { var test=document.getElementsByTagName("input"); alert(test.length); }s </script> </head> <body> <input name="Exforsys" type="text" size="30" /><br /> <input name="Exforsys" type="text" size="30" /><br /> <input type="button" onclick="Exforinput()" value="Click to see the number of tag with input as tag name" /> </body> </html> Output:


getSelection(): This method can be used to return a string containing any selected text in the current document. Example:

<html> <head> <script type="text/javascript"> function GetSelectedText () { if (document.getSelection) { var sel = document.getSelection (); alert (sel); } else { if (document.selection) { // Internet Explorer var textRange = document.selection.createRange (); alert (textRange.text); } } } </script> </head> <body> <div>Please select <b>all</b> or a <i>part</i> of this text.</div> <br /> <button onclick="GetSelectedText ()">Get selected text!</button> </body> </html> Output:

Element Object:

Represents the root node of the DOM tree, and actions on it will affect the entirety of the page. The document represents the whole page, its attributes indicate how it is defined and its methods allow access to its content. It is used with the keyword document: •

Attributes of Element Object: • Attributes • baseURI • childNodes • firstChild • lastChild • previousSibling • nextSibling • nodeName • nodeType • parentNode • ownerDocument • prefix • tagName • text • textContent

Methods of Element Object: • appendChild • cloneNode • compareDocumentPosition • getAttribute • gerAttributeNS • getAttributeNode • getElementByTagName • getFeature • hasAttribute • hasAttributes • hasChildNodes • insertBefore • isEqualNode • isSameNode • lookupPrefix • removeAttribute • removeAttributeNode • removeChild • replaceChild • setAttribute • setAttributeNode

nodeList Object:

The NodeList object represents an ordered list of nodes. The nodes in the NodeList can be accessed through their index number (starting from 0).The NodeList keeps itself up-to-date. If an element is deleted or added, in the node list or the XML document, the list is automatically updated. •

Attributes of nodeList Object: • length

Methods of nodeList Object: • item


• JavaScript can put dynamic text into an HTML page - A JavaScript statement like • JavaScript can be used to create cookies - A JavaScript...