SlideShare a Scribd company logo
CHAPTER FOUR
Dynamic HTML
HTML DOM
JavaScript
Compiled By: Seble N.
 DHTML
 The DOM
 Script Languages
 Introduction to JavaScript
 What is JS?
 What can a JavaScript do?
 Embedding JavaScript
 JavaScript programming Elements
‡ What is DHTML?
‡ DHTML stands for Dynamic HTML.
‡ DHTML is NOT a language or a web standard.
‡ DHTML means the combination of HTML, JavaScript, DOM and CSS.
‡ According to the World Wide Web Consortium (W3C): "Dynamic HTML is a term
used by some vendors to describe the combination of HTML, style sheets and
scripts that allows documents to be animated."
‡ The DOM (Document Object Model)
‡ is a platform and language-neutral interface that allows programs and scripts to
dynamically access and update the content, structure, and style of a document
‡ defines a standard for accessing documents like HTML and XML
‡ The W3c DOM is separated into 3 different parts:
‡ Core DOM - standard model for any structured document
‡ XML DOM - standard model for XML documents
‡ HTML DOM - standard model for HTML documents
‡ The HTML DOM is a standard object model and programming interface for
HTML
‡ It defines:
‡ The HTML elements as objects
‡ The properties of all HTML elements
‡ The methods to access all HTML elements
‡ The events for all HTML elements
‡ In other words: The HTML DOM is a standard for how to get, change, add, or
delete HTML elements
‡ According to the HTML DOM, everything in an HTML document is a node.
The HTML DOM says:
‡ The entire document is a document node
‡ Every HTML tag is an element node
‡ The text in the HTML elements are text nodes
‡ Every HTML attribute is an attribute node
‡ Comments are comment nodes
‡ The DOM views an HTML
document as a node-tree
‡ All nodes can be accessed
through the tree
‡ When a web page is
loaded, the browser
creates a Document
Object Model of the
page
‡ The programming interface to the DOM is defined by standard
properties and methods
‡ Property is a value that you can get or set (like changing the content of an
HTML element)
‡ Methods is an action you can do (like add or deleting an HTML element)
‡ HTML DOM Properties
‡ x.innerHTML - the inner text value
of x (an HTML element)
‡ x.nodeName - the name of x
‡ x.parentNode - the parent node of x
‡ x.childNodes - the child nodes of x
‡ x.attributes - the attributes nodes
of x
‡ x.nodeValue - the value of x
‡ HTML DOM Methods
‡ document.getElementById(id)
‡ get the element with a specified id
‡ document.getElementsByTagName(name)
‡ get all elements with a specified tag
name
‡ x.appendChild(node)
‡ insert a child node to x
‡ x.removeChild(node)
‡ remove a child node from x
Note: In the list above, x is a node object (HTML element).
‡ With the DOM, you can access every node in an HTML document
‡ You can access a node in three ways:
‡ By using the getElementById() method
‡ returns the element with the specified ID
‡ document.getElementById("someID");
‡ By using the getElementsByTagName() method
‡ returns all elements with a specified tag name.
‡ x=document.getElementsByTagName("p");
‡ The <p> elements in x can be accessed by index number
‡ By navigating the node tree, using the node relationships
‡ The three properties parentNode, firstChild, and lastChild follow the document structure and
allow short-distance travel in the document.
‡ x=document.getElementById("intro");
‡ text=x.firstChild.innerHTML;
‡ innerHTML
‡ is useful for returning or replacing the content of HTML element
‡ can be used to get or change any HTML element, including <html> and <body>
‡ Example
‡ The JavaScript code to get content of a <p> element with id "intro" in HTML document is:
‡ txt=document.getElementById("intro").innerHTML ;
‡ The JavaScript code to set new content to a <p> element with id "intro" in HTML
document is:
‡ document.getElementById("intro").innerHTML = “New Content” ;
‡ Changing attribute of an HTML element
‡ Syntax
‡ document.getElementById(id).attribute=new value;
‡ Example
‡ document.getElementById("myImage").src = "landscape.jpg";
‡ Value=document.getElementById("myImage").src;
‡ Changing HTML Style
‡ Syntax
‡ document.getElementById(id).style.property=new style ;
‡ Example
‡ document.getElementById("p2").style.color = "blue";
‡ Window Object
‡ is the top level object in the JavaScript hierarchy. The Window object represents a browser window
‡ Document Object:
‡ represents the entire HTML document and can be used to access all elements in a page.
‡ The Document object is part of the Window object and is accessed through the window.document property.
‡ Navigator Object
‡ is actually a JavaScript object, not an HTML DOM object that contains information about the client browser
‡ Screen Object:
‡ is actually a JavaScript object, not an HTML DOM object that contains information about the client's display screen
‡ History Object:
‡ is actually a JavaScript object, not an HTML DOM object
‡ consists of an array of URLs. These URLs are the URLs the user has visited within a browser window
‡ is part of the Window object and is accessed through the window.history property.
Introduction to Javascript
‡ Script Languages
‡ are subset of programming languages
‡ are not compiled to machine code by the user. Rather, another program
called the interpreter, runs the program and simulates its behavior
‡ are intended to be very fast to learn and write in programs
‡ There are two groups of script languages on the web:
‡ Client Side and Server Side Script languages
‡ Client Side Script
‡ refers to the class of computer programs on the web that are executed client-side, by the
user's web browser, instead of server-side (on the web server)
‡ is an important part of the Dynamic HTML (DHTML) concept, enabling web pages to be
scripted; that is, to have different and changing content depending on user input,
environmental conditions (such as the time of day), or other variables
‡ are not allowed to access the user's computer beyond the web browser application
‡ put less stress on the server because they don’t require processing on the server once
they’re downloaded
‡ Examples: JavaScript, VB script
‡ JavaScript
‡ is a client side scripting language
‡ is an interpreted language (means that scripts execute
without preliminary compilation)
‡ was designed to add interactivity to HTML pages
‡ is usually embedded directly into HTML pages
‡ With the help of the DOM, JavaScript gets all the power it needs to create
dynamic HTML:
‡ JavaScript can put dynamic text into an HTML page
‡ JavaScript can change attributes of HTML elements
‡ JavaScript can change CSS styles of HTML elements
‡ JavaScript can remove existing HTML elements and attributes
‡ JavaScript can add new HTML elements and attributes
‡ JavaScript can react to all existing HTML events in the page
‡ JavaScript can be used to validate form data
‡ JavaScript can be used to detect the visitor's browser
‡ JavaScript can be used to create cookies
‡ etc...
‡ You can place any number of scripts in an HTML
document
‡ JavaScript can be placed
‡ in the <head> tag
‡ in the <body> tag
‡ in external files
‡ JavaScript in <head> and/or <body>
‡ In HTML, JavaScript code must be inserted between <script> and </script>
tags
‡ Scripts that are defined outside of a function will be executed while the page is
loading.
‡ Scripts that are defined in a function are executed when "asked" for.
‡ Placing scripts at the bottom of the <body> element improves page load,
because HTML display is not blocked by scripts loading
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
‡ External JavaScript File
‡ are practical when the same code is used in many different web pages
‡ have .js file extension
‡ External scripts cannot contain <script> tags.
‡ You can place an external script reference in <head> or <body> as you like
‡ Placing JavaScripts in external files has some advantages:
‡ It separates HTML and code
‡ It makes HTML and JavaScript easier to read and maintain
‡ Cached JavaScript files can speed up page loads
‡ d<body>
<script type=“text/javascript” src="myScript.js"></script>
</body>
‡ JavaScript statements are separated by semicolons.
‡ JavaScript is a case-sensitive language
‡ JavaScript comments
‡ // Single Line Comment
‡ /* Multi line comment*/
‡ JavaScript ignores spaces, tabs, and newlines that appear in JavaScript
programs.
‡ JavaScript does NOT have any built-in print or display functions.
‡ JavaScript Display Possibilities
‡ JavaScript can "display" data in different ways:
‡ Writing into an alert box, using window.alert()
‡ Writing into the HTML output using document.write()
‡ Writing into an HTML element, using innerHTML
‡ Writing into the browser console, using console.log()
• For testing purposes, it is
convenient to use
document.write():
• Using document.write() after
an HTML document is fully
loaded, will delete all
existing HTML
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
• You can use an
alert box to
display data:
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
 The innerHTML
property defines an
HTML element
content
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").
innerHTML = “Hello there”;
</script>
</body>
 In your browser, you can
use the console.log()
method to display data
 Activate the browser
console with F12, and
select "Console" in the
menu.
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
console.log(5 + 6);
</script>
</body>
<script type="text/javascript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>
 JavaScript Variables
 the var keyword is used to define
variables
 can hold a value of any data type
 A variable may or may not be
declared before usage
 must begin with a letter or an
underscore character
 variable names should not start
with a numeral (0-9)
JavaScript Literals
Numbers are written with or without
decimals:
10.01 or 10
Strings are text, written within double or
single quotes:
"John Doe“ or 'John Doe'
NaN - is a JavaScript reserved word
indicating that a value is not a number
var x = 6;
var y = 6.5;
var name = “Abebe”
var alpha = ‘B’;
 JavaScript allows the same variable to contain different types of data values.
 Primitive data types
 Number: integer & floating-point numbers
 Boolean: logical values “true” or “false”
 String: a sequence of alphanumeric characters
 Composite data types (or Complex data types)
 Object: a named collection of data
 Array: a sequence of values
 Special data types
 Null: an initial value is assigned
 Undefined: the variable has been created but hasn’t be assigned a value
 The typeof Operator
 Used to find out
the type of a
JavaScript variable
var length = 16; // Number
var lastName = "Johnson"; // String
var cars = ["Saab", "Volvo", "BMW"]; // Array
var x = {firstName:"John", lastName:"Doe"}; // Object
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof false // Returns Boolean
typeof [1,2,3,4] // Returns object
typeof {name:'John', age:34} // Returns object
 Arithmetic Operators
 +, -, *, /, %, ++, --
 Assignment Operators
 +=, -=, *=, /=, %=
 Comparison Operators
 >, <, >=, <=, ==, ===, !=, !==
 Bitwise Operators
 &, |, ~, <<, >>
 String Operators
 txt1 = "John";
txt2 = "Doe";
txt3 = txt1 + " " + txt2;
 txt1 = "What a very ";
txt1 += "nice day";
Operator Description Comparing Returns
== equal to
5 == 5 true
5 == "5" true
===
equal value
and equal type
5=== 5 true
5 === "5" false
 JavaScript have the following conditional statements:
 Use if to specify a block of code to be executed, if a specified condition is
true
 Use else to specify a block of code to be executed, if the same condition is
false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed
<body>
<p>Click the button to get a time-based greeting:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var greeting;
var time = new Date().getHours();
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening"; }
document.getElementById("demo").innerHTML = greeting;
}
</script>
</body>
<body>
<p id="demo"></p>
<script>
var text;
switch (new Date().getDay()) {
case 1:
case 2:
case 3:
default:
text = "Looking forward to the Weekend";
break;
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
 JavaScript supports different kinds of loops:
 for
 loops through a block of code a number of times
 for/in
 loops through the properties of an object
 while
 loops through a block of code while a specified condition is true
 do/while
 also loops through a block of code while a specified condition is true
 The for loop has the following syntax:
<p id="demo"></p>
<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i, len, text;
for (i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
 for/in statement loops through the properties of
an object
 The while loop loops through a block of code as long as
a specified condition is true.
 This loop executes the code block at least once, before checking if the
condition is true, then it will repeat the loop as long as the condition is
true.
 Break
 used to jump out of a loop or a switch block
 breaks the loop and continues executing the code after the loop (if any):
 Continue
 breaks one iteration (in the loop), if a specified condition occurs, and continues with the next
iteration in the loop
 Creating an Array
 Syntax:
 var array-name = [item1, item2, ...];
 Using the new keyword
 Example:
 var cars = ["Saab", "Volvo", "BMW"];
 var cars = new Array("Saab", "Volvo", "BMW");
 Array can hold different objects/datatypes
 Array index starts with 0
 Arrays use numbers to access its "elements”
 var person = ["John", "Doe", 46];
 person[0] returns John
 The length Property
 returns the length of an array
 Example
 var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length;
 Adding Array Elements
 The easiest way to add a new element to an array is using the push
method:
 Example
 var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon");
 Sorting Array Elements
 var y = fruits.sort(); // sort cars in alphabetical order
 JavaScript objects are containers for
named values
 Accessing Object properties
 objectName.propertyName or
objectName["propertyName"]
 Example
 person.firstName or person[“firstName”]
 Accessing Object Methods
 objectName.methodName()
 Example
 person.fullName();
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " +
this.lastName;
}
};
 A string can be any text inside quotes. You can use single or double quotes:
 var carname = 'Volvo XC60';
 You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:
 var answer = "It's alright";
 The other solution is to use escape characters
 var answer = ‘It’s alright’;
 Other escape characters: ’ , ” ,  , n, t ….
 The length of a string is found in the built in property length
 answer.length
Event Description
charAt() Returns the character at the specified index (position)
concat() Joins two or more strings, and returns a copy of the joined strings
match()
Searches a string for a match against a regular expression, and
returns the matches
toLowerCase() Converts a string to lowercase letters
trim() Removes whitespace from both ends of a string
split() Splits a string into an array of substrings
 A date consists of a year, a month, a day, an hour, a minute, a second,
and milliseconds.
 Date objects are created with the new Date() constructor
 Using new Date(), creates a new date object with the current date and
time
 When you display a date object in HTML, it is automatically
converted to a string, with the toString() method.
<p id="demo"></p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
Get Methods Description
getDate() Get the day as a number (1-31)
getDay()
Get the weekday as a number
(0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
<p id="demo"></p>
<script>
var d = new Date();
var p=document.getElementById("demo");
p.innerHTML = d.getDate() + " " +
d.getDay() + " " +
d.getMonth() + " " +
d.getFullYear();
</script>
 The Math Object
 allows to perform mathematical tasks
 includes several mathematical methods
 Math.min() and Math.max()
 can be used to find the lowest or highest value in a list of arguments
 Example: Math.min(0, 150, 30, 20, -8, -200); // returns -200
 Math.random()
 returns a random number between 0 (inclusive), and 1 (exclusive):
 Math.round()
 rounds a number to the nearest integer
 Example: Math.round(4.7); // returns 5
 Function Syntax
 Function parameters are the names listed in the function definition
 Function arguments are the real values received by the function when it is invoked.the function, the
arguments behave as local variables.
 Function Invocation
 The code inside the function will execute when "something" invokes (calls) the function:
 When an event occurs (when a user clicks a button)
 When it is invoked (called) from JavaScript code
 Automatically (self invoked)
 Function Return
 When JavaScript reaches a return statement, the function will stop executing.
 If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking
statement.
function name(para1, para2) {
code to be executed
}
var x = myFunction(4, 3);
function myFunction(a, b) {
return a * b;
}
 HTML Events
 An HTML event can be something the browser does, or something a user does
 Some examples of HTML events:
 An HTML web page has finished loading
 An HTML input field was changed
 An HTML button was clicked
 JavaScript lets you execute code when events are detected.
 HTML allows event handler attributes, with JavaScript code, to be added to HTML
elements
 Syntax: <some-HTML-element some-event="some JavaScript">
 Ex: <button onclick=‘displayDate();‘>The time is?</button>
 The onload event
 occurs when an object has been loaded
 is most often used with the <body>
element to execute a script once a web
page has completely loaded all content
 can be used to check the visitor's browser
type and browser version, and load the
proper version of the web page based on
the information
 can also be used to deal with cookies
 The onuload event
 occurs once a page has
unloaded
 occurs when the user navigates
away from the page (by
clicking on a link, submitting a
form, closing the browser
window, etc.).
 onsubmit event
 occurs when you try to submit a form
 often used to trigger a form validator function
 In the following example: if validate() function returns true, the form will be submitted,
otherwise it will not submit the data
<script>
function validation() {
all validation goes here .........
return either true or false
}
</script>
<body>
<form method="POST" action=“reg.asp" onsubmit="return validate();">
.......
<input type="submit" value="Submit" />
</form>
</body>
 The onmouseover event
 triggers when you bring your mouse over any element and
 The onmouseout event
 triggers when you move your mouse out from an element
<script>
function over() {
document.getElementById("h2").innerHTML="Mouse Over";}
function out() {
document.getElementById("h2").innerHTML="Mouse Out";}
</script>
<body>
<div onmouseout="out();" onmouseover="over();" >
<h2 id="h2"> This is inside the division </h2>
</div>
</body>
Event Description
ontouchstart
occurs when a finger is placed
on a touch screen
onclick The user clicks an HTML element
onplay
occurs when the media has
been started
onoffline
occurs when the browser starts
to work offline
onkeydown The user pushes a keyboard key
onload
The browser has finished loading
the page
Event Description
ondblclick
occurs when the user double-clicks
on an element
oninput
occurs when an element gets user
input
onsubmit occurs when a form is submitted
ondrag
occurs when an element is being
dragged
Oncopy
occurs when the user copies the
content of an element
onbeforeprint
occurs when a page is about to be
printed
 Regular Expression
 Is a special text string for describing a search pattern
 you can use this search pattern to describe what you are searching for
 You can think of regular expressions as wildcards(*, ? …)
 Application
 To check if a particular string that follows some pattern exists in some text or another
string
 To check if user’s input follows the expected input type
 Example:
 E-mail input
 Phone number
 Password
 The JavaScript RegExp class represents regular expressions
 Syntax
 var pattern = new RegExp(pattern, attributes);
 var pattern = /pattern/attributes;
 pattern:
 A string that specifies the pattern of the regular expression
 attributes:
 An optional string containing any of the "g", "i", and "m" attributes that
specify global, case-insensitive, and multiline matches, respectively.
Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |
Meta
Character
Description
d Find a digit
s Find a whitespace character
b Find a match at the beginning or at the end of a word
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
Introduction to Javascript
 Using the RegExp method test()
 It searches a string for a pattern, and returns true or false, depending on the result.
 Example
var patt = /[a-z]+e/;
patt.test("The best things in life are free!");
 Using the RegExp method exec()
 It searches a string for a specified pattern, and returns the found text.
 If no match is found, it returns null.
 Example
/[a-z]+e/.exec("The best things in life are free!");
 Using String search() With a Regular Expression
 Returns the index the found text starts at
 Use a regular expression to do a case-insensitive search for "w3schools" in a string:
 var str = "Visit w3SCHools";
var n = str.search(/w3schools/i);
 Use String match() With a Regular Expression
 searches a string for a match against a regular expression, and returns the matches, as an Array object or returns
null if no match is found.
 Syntax: string.match(regexp)
 var str = “The rain in SPAIN stays mainly in the plain ";
var res = str.match(/ain/gi);
 The result in res will be:
 ain,AIN,ain,ain
 A web page can be refreshed using JavaScript location.reload method
 The method can be called automatically upon an event or simply when
the user clicks on a link
 <a href="location.reload(true);">Refresh Page</a>
 Auto Refresh
 setTimeout() is a built-in JavaScript function which can be used to execute
another function after a given time interval
 <body onload='setTimeout("location.reload(true);",2000);’>
 There could be various reasons why you would like to redirect a user
from the original page
1. You did not like the name of your domain and you are moving to a new
one
2. You have built-up various pages based on browser versions or their
names or may be based on different countries, then you can use client-
side page redirection to land your users on the appropriate page
3. Etc..
 Auto redirect a page
<body onload="window.location='www.google.com';">
 Auto redirect a page after sometime
<script>
function redirect(){
window.location='www.google.com';
}
</script>
<body onload=“setTimeout(“redirect()“,5000);”>
<p>You will be redirected to google.com in 5 seconds.
</body>
 To redirect visitors onto a different page based on their browser type
var browsername=navigator.appName;
if( browsername == "Netscape" ) {
window.location="http://www.location.com/ns.htm";
}
else if ( browsername =="Microsoft Internet Explorer") {
window.location="http://www.location.com/ie.htm";
}
else {
window.location="http://www.location.com/other.htm";
}
 The JavaScript print function window.print() prints the current
web page when executed
 You can call this function directly using the onclick event as
shown in the following example
 <input type="button" value="Print"
onclick="window.print()" />
 What are cookies?
 are small files which are stored on a user's computer
 are designed to hold a modest amount of data specific to a particular client and website
 Each cookie is a small lookup table containing pairs of (key, data) values
 can be accessed either by a client side or server side script language
 Why do we need cookies?
 Once a web server is done with sending a web page to a browser, the connection is shut
down, and the server forgets everything about the user
 Cookies were invented to solve the problem "how to remember information about the user"
 How Cookies Work?
 When a user visits a web page for the first time, his/her name can be requested and be
stored in a cookie.
 Next time the user requests the page, cookies belonging to the page is added to the request
 This way the server gets the necessary data to "remember" information about users
 Cookies are a plain text data record of 5 variable-length fields:
 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.
 Name: The name of the cookie
 Value: The data that is stored on the cookie
 JavaScript can create, read, and delete cookies with the
document.cookie property.
 With JavaScript, a cookie can be created like this:
document.cookie="username=John Doe;”
 You can also add an expiry date. By default, the cookie is deleted
when the browser is closed:
document.cookie="username=John Doe; expires=Thu,18 Dec
2013 12:00:00 UTC;”
 Read a Cookie with JavaScript
 With JavaScript, cookies can be read like this:
var x = document.cookie;
 document.cookie will return all cookies in one string much like:
cookie1=value; cookie2=value; cookie3=value;
 Change a Cookie with JavaScript
 With JavaScript, you can change a cookie the same way as you create it:
 document.cookie="username=John Smith; expires=Thu, 18 Dec 2013
12:00:00 UTC; path=/";
 Delete a Cookie with JavaScript
 Deleting a cookie is very simple. Just set the expires parameter to a passed
date:
 document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00
UTC";
 Note that you don't have to specify a cookie value when you delete a cookie.
<script type="text/javascript">
function WriteCookie(){
if( document.myform.customer.value == "" ){
alert ("Enter some value!");
return;
}
cookievalue= document.myform.customer.value;
document.cookie="name=" + cookievalue;
}
</script>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
<script type="text/javascript">
function ReadCookie(){
var allcookies = document.cookie;
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value); }
}
</script><body>
<form name="myform" action="">
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form></body>

More Related Content

PDF
Introduction to HTML
PPTX
Java script
PPTX
Lab #2: Introduction to Javascript
PDF
Introduction to Bootstrap
PPTX
Javascript 101
PDF
Introduction to CSS3
PDF
HTML5: features with examples
Introduction to HTML
Java script
Lab #2: Introduction to Javascript
Introduction to Bootstrap
Javascript 101
Introduction to CSS3
HTML5: features with examples

What's hot (20)

PPT
javaScript.ppt
PPTX
Html5 semantics
PPT
Advanced Cascading Style Sheets
PPTX
Html 5-tables-forms-frames (1)
PPTX
Angular Data Binding
PPTX
ODP
CSS Basics
PDF
CSS Day: CSS Grid Layout
PDF
3. Java Script
PPTX
PPTX
Javascript
PPTX
Introduction to JavaScript Basics.
PDF
Intro to HTML and CSS basics
PPTX
Html5 tutorial for beginners
PDF
HTML and CSS crash course!
PDF
What is JavaScript? Edureka
PPTX
Bootstrap 5 ppt
PPT
jQuery Ajax
PPT
Css lecture notes
javaScript.ppt
Html5 semantics
Advanced Cascading Style Sheets
Html 5-tables-forms-frames (1)
Angular Data Binding
CSS Basics
CSS Day: CSS Grid Layout
3. Java Script
Javascript
Introduction to JavaScript Basics.
Intro to HTML and CSS basics
Html5 tutorial for beginners
HTML and CSS crash course!
What is JavaScript? Edureka
Bootstrap 5 ppt
jQuery Ajax
Css lecture notes
Ad

Similar to Introduction to Javascript (20)

PPTX
Dom date and objects and event handling
PPTX
Web technologies-course 09.pptx
PPTX
Web Technology Part 3
PDF
Java script
PPT
6867389.ppt
PPT
6867389 (1).ppt
PPT
6867389.ppt
DOCX
DOM(Document Object Model) in javascript
PPTX
Part 7
PPTX
FYBSC IT Web Programming Unit III Document Object
PPTX
Javascript for web Programming creating and embedding with html
PPTX
WEB TECHNOLOGY Unit-4.pptx
PPTX
Internet protocol second unit IIPPT.pptx
PPTX
Javascript part 2 DOM.pptx
PPTX
DOM and Events
PDF
JS BASICS JAVA SCRIPT SCRIPTING
PPTX
Introduction to JavaScript, functions, DOM
PDF
Intro to JavaScript
PPTX
01 Introduction - JavaScript Development
PPTX
Introduction to java script, how to include java in HTML
Dom date and objects and event handling
Web technologies-course 09.pptx
Web Technology Part 3
Java script
6867389.ppt
6867389 (1).ppt
6867389.ppt
DOM(Document Object Model) in javascript
Part 7
FYBSC IT Web Programming Unit III Document Object
Javascript for web Programming creating and embedding with html
WEB TECHNOLOGY Unit-4.pptx
Internet protocol second unit IIPPT.pptx
Javascript part 2 DOM.pptx
DOM and Events
JS BASICS JAVA SCRIPT SCRIPTING
Introduction to JavaScript, functions, DOM
Intro to JavaScript
01 Introduction - JavaScript Development
Introduction to java script, how to include java in HTML
Ad

More from Seble Nigussie (7)

PDF
Fundamentals of programming with C++
PDF
Introduction to JSON & Ajax
PDF
Introduction to jQuery
PDF
Introduction to Bootstrap
PDF
Flexbox, Grid and Sass
PDF
Introduction to HTTP
PDF
Introduction to Microprocessors
Fundamentals of programming with C++
Introduction to JSON & Ajax
Introduction to jQuery
Introduction to Bootstrap
Flexbox, Grid and Sass
Introduction to HTTP
Introduction to Microprocessors

Recently uploaded (20)

PDF
Insiders guide to clinical Medicine.pdf
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PDF
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PPTX
How to Manage Starshipit in Odoo 18 - Odoo Slides
PDF
LDMMIA Reiki Yoga S2 L3 Vod Sample Preview
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
PPTX
Congenital Hypothyroidism pptx
PDF
Sunset Boulevard Student Revision Booklet
PPTX
Software Engineering BSC DS UNIT 1 .pptx
PPTX
Onica Farming 24rsclub profitable farm business
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
PDF
What Is Coercive Control? Understanding and Recognizing Hidden Abuse
Insiders guide to clinical Medicine.pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Cardiovascular Pharmacology for pharmacy students.pptx
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
How to Manage Starshipit in Odoo 18 - Odoo Slides
LDMMIA Reiki Yoga S2 L3 Vod Sample Preview
Renaissance Architecture: A Journey from Faith to Humanism
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
Congenital Hypothyroidism pptx
Sunset Boulevard Student Revision Booklet
Software Engineering BSC DS UNIT 1 .pptx
Onica Farming 24rsclub profitable farm business
Week 4 Term 3 Study Techniques revisited.pptx
UPPER GASTRO INTESTINAL DISORDER.docx
human mycosis Human fungal infections are called human mycosis..pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
What Is Coercive Control? Understanding and Recognizing Hidden Abuse

Introduction to Javascript

  • 1. CHAPTER FOUR Dynamic HTML HTML DOM JavaScript Compiled By: Seble N.
  • 2.  DHTML  The DOM  Script Languages  Introduction to JavaScript  What is JS?  What can a JavaScript do?  Embedding JavaScript  JavaScript programming Elements
  • 3. ‡ What is DHTML? ‡ DHTML stands for Dynamic HTML. ‡ DHTML is NOT a language or a web standard. ‡ DHTML means the combination of HTML, JavaScript, DOM and CSS. ‡ According to the World Wide Web Consortium (W3C): "Dynamic HTML is a term used by some vendors to describe the combination of HTML, style sheets and scripts that allows documents to be animated."
  • 4. ‡ The DOM (Document Object Model) ‡ is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document ‡ defines a standard for accessing documents like HTML and XML ‡ The W3c DOM is separated into 3 different parts: ‡ Core DOM - standard model for any structured document ‡ XML DOM - standard model for XML documents ‡ HTML DOM - standard model for HTML documents
  • 5. ‡ The HTML DOM is a standard object model and programming interface for HTML ‡ It defines: ‡ The HTML elements as objects ‡ The properties of all HTML elements ‡ The methods to access all HTML elements ‡ The events for all HTML elements ‡ In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements
  • 6. ‡ According to the HTML DOM, everything in an HTML document is a node. The HTML DOM says: ‡ The entire document is a document node ‡ Every HTML tag is an element node ‡ The text in the HTML elements are text nodes ‡ Every HTML attribute is an attribute node ‡ Comments are comment nodes
  • 7. ‡ The DOM views an HTML document as a node-tree ‡ All nodes can be accessed through the tree ‡ When a web page is loaded, the browser creates a Document Object Model of the page
  • 8. ‡ The programming interface to the DOM is defined by standard properties and methods ‡ Property is a value that you can get or set (like changing the content of an HTML element) ‡ Methods is an action you can do (like add or deleting an HTML element)
  • 9. ‡ HTML DOM Properties ‡ x.innerHTML - the inner text value of x (an HTML element) ‡ x.nodeName - the name of x ‡ x.parentNode - the parent node of x ‡ x.childNodes - the child nodes of x ‡ x.attributes - the attributes nodes of x ‡ x.nodeValue - the value of x ‡ HTML DOM Methods ‡ document.getElementById(id) ‡ get the element with a specified id ‡ document.getElementsByTagName(name) ‡ get all elements with a specified tag name ‡ x.appendChild(node) ‡ insert a child node to x ‡ x.removeChild(node) ‡ remove a child node from x Note: In the list above, x is a node object (HTML element).
  • 10. ‡ With the DOM, you can access every node in an HTML document ‡ You can access a node in three ways: ‡ By using the getElementById() method ‡ returns the element with the specified ID ‡ document.getElementById("someID"); ‡ By using the getElementsByTagName() method ‡ returns all elements with a specified tag name. ‡ x=document.getElementsByTagName("p"); ‡ The <p> elements in x can be accessed by index number ‡ By navigating the node tree, using the node relationships ‡ The three properties parentNode, firstChild, and lastChild follow the document structure and allow short-distance travel in the document. ‡ x=document.getElementById("intro"); ‡ text=x.firstChild.innerHTML;
  • 11. ‡ innerHTML ‡ is useful for returning or replacing the content of HTML element ‡ can be used to get or change any HTML element, including <html> and <body> ‡ Example ‡ The JavaScript code to get content of a <p> element with id "intro" in HTML document is: ‡ txt=document.getElementById("intro").innerHTML ; ‡ The JavaScript code to set new content to a <p> element with id "intro" in HTML document is: ‡ document.getElementById("intro").innerHTML = “New Content” ;
  • 12. ‡ Changing attribute of an HTML element ‡ Syntax ‡ document.getElementById(id).attribute=new value; ‡ Example ‡ document.getElementById("myImage").src = "landscape.jpg"; ‡ Value=document.getElementById("myImage").src; ‡ Changing HTML Style ‡ Syntax ‡ document.getElementById(id).style.property=new style ; ‡ Example ‡ document.getElementById("p2").style.color = "blue";
  • 13. ‡ Window Object ‡ is the top level object in the JavaScript hierarchy. The Window object represents a browser window ‡ Document Object: ‡ represents the entire HTML document and can be used to access all elements in a page. ‡ The Document object is part of the Window object and is accessed through the window.document property. ‡ Navigator Object ‡ is actually a JavaScript object, not an HTML DOM object that contains information about the client browser ‡ Screen Object: ‡ is actually a JavaScript object, not an HTML DOM object that contains information about the client's display screen ‡ History Object: ‡ is actually a JavaScript object, not an HTML DOM object ‡ consists of an array of URLs. These URLs are the URLs the user has visited within a browser window ‡ is part of the Window object and is accessed through the window.history property.
  • 15. ‡ Script Languages ‡ are subset of programming languages ‡ are not compiled to machine code by the user. Rather, another program called the interpreter, runs the program and simulates its behavior ‡ are intended to be very fast to learn and write in programs ‡ There are two groups of script languages on the web: ‡ Client Side and Server Side Script languages
  • 16. ‡ Client Side Script ‡ refers to the class of computer programs on the web that are executed client-side, by the user's web browser, instead of server-side (on the web server) ‡ is an important part of the Dynamic HTML (DHTML) concept, enabling web pages to be scripted; that is, to have different and changing content depending on user input, environmental conditions (such as the time of day), or other variables ‡ are not allowed to access the user's computer beyond the web browser application ‡ put less stress on the server because they don’t require processing on the server once they’re downloaded ‡ Examples: JavaScript, VB script
  • 17. ‡ JavaScript ‡ is a client side scripting language ‡ is an interpreted language (means that scripts execute without preliminary compilation) ‡ was designed to add interactivity to HTML pages ‡ is usually embedded directly into HTML pages
  • 18. ‡ With the help of the DOM, JavaScript gets all the power it needs to create dynamic HTML: ‡ JavaScript can put dynamic text into an HTML page ‡ JavaScript can change attributes of HTML elements ‡ JavaScript can change CSS styles of HTML elements ‡ JavaScript can remove existing HTML elements and attributes ‡ JavaScript can add new HTML elements and attributes ‡ JavaScript can react to all existing HTML events in the page ‡ JavaScript can be used to validate form data ‡ JavaScript can be used to detect the visitor's browser ‡ JavaScript can be used to create cookies ‡ etc...
  • 19. ‡ You can place any number of scripts in an HTML document ‡ JavaScript can be placed ‡ in the <head> tag ‡ in the <body> tag ‡ in external files
  • 20. ‡ JavaScript in <head> and/or <body> ‡ In HTML, JavaScript code must be inserted between <script> and </script> tags ‡ Scripts that are defined outside of a function will be executed while the page is loading. ‡ Scripts that are defined in a function are executed when "asked" for. ‡ Placing scripts at the bottom of the <body> element improves page load, because HTML display is not blocked by scripts loading <script> document.getElementById("demo").innerHTML = "My First JavaScript"; </script>
  • 21. ‡ External JavaScript File ‡ are practical when the same code is used in many different web pages ‡ have .js file extension ‡ External scripts cannot contain <script> tags. ‡ You can place an external script reference in <head> or <body> as you like ‡ Placing JavaScripts in external files has some advantages: ‡ It separates HTML and code ‡ It makes HTML and JavaScript easier to read and maintain ‡ Cached JavaScript files can speed up page loads ‡ d<body> <script type=“text/javascript” src="myScript.js"></script> </body>
  • 22. ‡ JavaScript statements are separated by semicolons. ‡ JavaScript is a case-sensitive language ‡ JavaScript comments ‡ // Single Line Comment ‡ /* Multi line comment*/ ‡ JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
  • 23. ‡ JavaScript does NOT have any built-in print or display functions. ‡ JavaScript Display Possibilities ‡ JavaScript can "display" data in different ways: ‡ Writing into an alert box, using window.alert() ‡ Writing into the HTML output using document.write() ‡ Writing into an HTML element, using innerHTML ‡ Writing into the browser console, using console.log()
  • 24. • For testing purposes, it is convenient to use document.write(): • Using document.write() after an HTML document is fully loaded, will delete all existing HTML <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> document.write(5 + 6); </script> </body>
  • 25. • You can use an alert box to display data: <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> window.alert(5 + 6); </script> </body>
  • 26.  The innerHTML property defines an HTML element content <body> <h1>My First Web Page</h1> <p>My First Paragraph</p> <p id="demo"></p> <script> document.getElementById("demo"). innerHTML = “Hello there”; </script> </body>
  • 27.  In your browser, you can use the console.log() method to display data  Activate the browser console with F12, and select "Console" in the menu. <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> console.log(5 + 6); </script> </body>
  • 28. <script type="text/javascript"> alert("This is an Alert method"); confirm("Are you OK?"); prompt("What is your name?"); prompt("How old are you?","20"); </script>
  • 29.  JavaScript Variables  the var keyword is used to define variables  can hold a value of any data type  A variable may or may not be declared before usage  must begin with a letter or an underscore character  variable names should not start with a numeral (0-9) JavaScript Literals Numbers are written with or without decimals: 10.01 or 10 Strings are text, written within double or single quotes: "John Doe“ or 'John Doe' NaN - is a JavaScript reserved word indicating that a value is not a number var x = 6; var y = 6.5; var name = “Abebe” var alpha = ‘B’;
  • 30.  JavaScript allows the same variable to contain different types of data values.  Primitive data types  Number: integer & floating-point numbers  Boolean: logical values “true” or “false”  String: a sequence of alphanumeric characters  Composite data types (or Complex data types)  Object: a named collection of data  Array: a sequence of values  Special data types  Null: an initial value is assigned  Undefined: the variable has been created but hasn’t be assigned a value
  • 31.  The typeof Operator  Used to find out the type of a JavaScript variable var length = 16; // Number var lastName = "Johnson"; // String var cars = ["Saab", "Volvo", "BMW"]; // Array var x = {firstName:"John", lastName:"Doe"}; // Object typeof "John" // Returns string typeof 3.14 // Returns number typeof false // Returns Boolean typeof [1,2,3,4] // Returns object typeof {name:'John', age:34} // Returns object
  • 32.  Arithmetic Operators  +, -, *, /, %, ++, --  Assignment Operators  +=, -=, *=, /=, %=  Comparison Operators  >, <, >=, <=, ==, ===, !=, !==  Bitwise Operators  &, |, ~, <<, >>  String Operators  txt1 = "John"; txt2 = "Doe"; txt3 = txt1 + " " + txt2;  txt1 = "What a very "; txt1 += "nice day"; Operator Description Comparing Returns == equal to 5 == 5 true 5 == "5" true === equal value and equal type 5=== 5 true 5 === "5" false
  • 33.  JavaScript have the following conditional statements:  Use if to specify a block of code to be executed, if a specified condition is true  Use else to specify a block of code to be executed, if the same condition is false  Use else if to specify a new condition to test, if the first condition is false  Use switch to specify many alternative blocks of code to be executed
  • 34. <body> <p>Click the button to get a time-based greeting:</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var greeting; var time = new Date().getHours(); if (time < 10) { greeting = "Good morning"; } else if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; } document.getElementById("demo").innerHTML = greeting; } </script> </body> <body> <p id="demo"></p> <script> var text; switch (new Date().getDay()) { case 1: case 2: case 3: default: text = "Looking forward to the Weekend"; break; case 4: case 5: text = "Soon it is Weekend"; break; case 0: case 6: text = "It is Weekend"; } document.getElementById("demo").innerHTML = text; </script> </body>
  • 35.  JavaScript supports different kinds of loops:  for  loops through a block of code a number of times  for/in  loops through the properties of an object  while  loops through a block of code while a specified condition is true  do/while  also loops through a block of code while a specified condition is true
  • 36.  The for loop has the following syntax: <p id="demo"></p> <script> var cars = ["BMW", "Volvo", "Saab", "Ford"]; var i, len, text; for (i = 0, len = cars.length, text = ""; i < len; i++) { text += cars[i] + "<br>"; } document.getElementById("demo").innerHTML = text; </script>
  • 37.  for/in statement loops through the properties of an object
  • 38.  The while loop loops through a block of code as long as a specified condition is true.
  • 39.  This loop executes the code block at least once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
  • 40.  Break  used to jump out of a loop or a switch block  breaks the loop and continues executing the code after the loop (if any):  Continue  breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop
  • 41.  Creating an Array  Syntax:  var array-name = [item1, item2, ...];  Using the new keyword  Example:  var cars = ["Saab", "Volvo", "BMW"];  var cars = new Array("Saab", "Volvo", "BMW");  Array can hold different objects/datatypes  Array index starts with 0  Arrays use numbers to access its "elements”  var person = ["John", "Doe", 46];  person[0] returns John
  • 42.  The length Property  returns the length of an array  Example  var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.length;  Adding Array Elements  The easiest way to add a new element to an array is using the push method:  Example  var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Lemon");  Sorting Array Elements  var y = fruits.sort(); // sort cars in alphabetical order
  • 43.  JavaScript objects are containers for named values  Accessing Object properties  objectName.propertyName or objectName["propertyName"]  Example  person.firstName or person[“firstName”]  Accessing Object Methods  objectName.methodName()  Example  person.fullName(); var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } };
  • 44.  A string can be any text inside quotes. You can use single or double quotes:  var carname = 'Volvo XC60';  You can use quotes inside a string, as long as they don't match the quotes surrounding the string:  var answer = "It's alright";  The other solution is to use escape characters  var answer = ‘It’s alright’;  Other escape characters: ’ , ” , , n, t ….  The length of a string is found in the built in property length  answer.length
  • 45. Event Description charAt() Returns the character at the specified index (position) concat() Joins two or more strings, and returns a copy of the joined strings match() Searches a string for a match against a regular expression, and returns the matches toLowerCase() Converts a string to lowercase letters trim() Removes whitespace from both ends of a string split() Splits a string into an array of substrings
  • 46.  A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.  Date objects are created with the new Date() constructor  Using new Date(), creates a new date object with the current date and time  When you display a date object in HTML, it is automatically converted to a string, with the toString() method. <p id="demo"></p> <script> var d = new Date(); document.getElementById("demo").innerHTML = d; </script>
  • 47. Get Methods Description getDate() Get the day as a number (1-31) getDay() Get the weekday as a number (0-6) getFullYear() Get the four digit year (yyyy) getHours() Get the hour (0-23) getMilliseconds() Get the milliseconds (0-999) getMinutes() Get the minutes (0-59) getMonth() Get the month (0-11) getSeconds() Get the seconds (0-59) <p id="demo"></p> <script> var d = new Date(); var p=document.getElementById("demo"); p.innerHTML = d.getDate() + " " + d.getDay() + " " + d.getMonth() + " " + d.getFullYear(); </script>
  • 48.  The Math Object  allows to perform mathematical tasks  includes several mathematical methods  Math.min() and Math.max()  can be used to find the lowest or highest value in a list of arguments  Example: Math.min(0, 150, 30, 20, -8, -200); // returns -200  Math.random()  returns a random number between 0 (inclusive), and 1 (exclusive):  Math.round()  rounds a number to the nearest integer  Example: Math.round(4.7); // returns 5
  • 49.  Function Syntax  Function parameters are the names listed in the function definition  Function arguments are the real values received by the function when it is invoked.the function, the arguments behave as local variables.  Function Invocation  The code inside the function will execute when "something" invokes (calls) the function:  When an event occurs (when a user clicks a button)  When it is invoked (called) from JavaScript code  Automatically (self invoked)  Function Return  When JavaScript reaches a return statement, the function will stop executing.  If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement. function name(para1, para2) { code to be executed } var x = myFunction(4, 3); function myFunction(a, b) { return a * b; }
  • 50.  HTML Events  An HTML event can be something the browser does, or something a user does  Some examples of HTML events:  An HTML web page has finished loading  An HTML input field was changed  An HTML button was clicked  JavaScript lets you execute code when events are detected.  HTML allows event handler attributes, with JavaScript code, to be added to HTML elements  Syntax: <some-HTML-element some-event="some JavaScript">  Ex: <button onclick=‘displayDate();‘>The time is?</button>
  • 51.  The onload event  occurs when an object has been loaded  is most often used with the <body> element to execute a script once a web page has completely loaded all content  can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information  can also be used to deal with cookies  The onuload event  occurs once a page has unloaded  occurs when the user navigates away from the page (by clicking on a link, submitting a form, closing the browser window, etc.).
  • 52.  onsubmit event  occurs when you try to submit a form  often used to trigger a form validator function  In the following example: if validate() function returns true, the form will be submitted, otherwise it will not submit the data <script> function validation() { all validation goes here ......... return either true or false } </script> <body> <form method="POST" action=“reg.asp" onsubmit="return validate();"> ....... <input type="submit" value="Submit" /> </form> </body>
  • 53.  The onmouseover event  triggers when you bring your mouse over any element and  The onmouseout event  triggers when you move your mouse out from an element <script> function over() { document.getElementById("h2").innerHTML="Mouse Over";} function out() { document.getElementById("h2").innerHTML="Mouse Out";} </script> <body> <div onmouseout="out();" onmouseover="over();" > <h2 id="h2"> This is inside the division </h2> </div> </body>
  • 54. Event Description ontouchstart occurs when a finger is placed on a touch screen onclick The user clicks an HTML element onplay occurs when the media has been started onoffline occurs when the browser starts to work offline onkeydown The user pushes a keyboard key onload The browser has finished loading the page Event Description ondblclick occurs when the user double-clicks on an element oninput occurs when an element gets user input onsubmit occurs when a form is submitted ondrag occurs when an element is being dragged Oncopy occurs when the user copies the content of an element onbeforeprint occurs when a page is about to be printed
  • 55.  Regular Expression  Is a special text string for describing a search pattern  you can use this search pattern to describe what you are searching for  You can think of regular expressions as wildcards(*, ? …)  Application  To check if a particular string that follows some pattern exists in some text or another string  To check if user’s input follows the expected input type  Example:  E-mail input  Phone number  Password
  • 56.  The JavaScript RegExp class represents regular expressions  Syntax  var pattern = new RegExp(pattern, attributes);  var pattern = /pattern/attributes;  pattern:  A string that specifies the pattern of the regular expression  attributes:  An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multiline matches, respectively.
  • 57. Expression Description [abc] Find any of the characters between the brackets [0-9] Find any of the digits between the brackets (x|y) Find any of the alternatives separated with | Meta Character Description d Find a digit s Find a whitespace character b Find a match at the beginning or at the end of a word Quantifier Description n+ Matches any string that contains at least one n n* Matches any string that contains zero or more occurrences of n n? Matches any string that contains zero or one occurrences of n
  • 59.  Using the RegExp method test()  It searches a string for a pattern, and returns true or false, depending on the result.  Example var patt = /[a-z]+e/; patt.test("The best things in life are free!");  Using the RegExp method exec()  It searches a string for a specified pattern, and returns the found text.  If no match is found, it returns null.  Example /[a-z]+e/.exec("The best things in life are free!");
  • 60.  Using String search() With a Regular Expression  Returns the index the found text starts at  Use a regular expression to do a case-insensitive search for "w3schools" in a string:  var str = "Visit w3SCHools"; var n = str.search(/w3schools/i);  Use String match() With a Regular Expression  searches a string for a match against a regular expression, and returns the matches, as an Array object or returns null if no match is found.  Syntax: string.match(regexp)  var str = “The rain in SPAIN stays mainly in the plain "; var res = str.match(/ain/gi);  The result in res will be:  ain,AIN,ain,ain
  • 61.  A web page can be refreshed using JavaScript location.reload method  The method can be called automatically upon an event or simply when the user clicks on a link  <a href="location.reload(true);">Refresh Page</a>  Auto Refresh  setTimeout() is a built-in JavaScript function which can be used to execute another function after a given time interval  <body onload='setTimeout("location.reload(true);",2000);’>
  • 62.  There could be various reasons why you would like to redirect a user from the original page 1. You did not like the name of your domain and you are moving to a new one 2. You have built-up various pages based on browser versions or their names or may be based on different countries, then you can use client- side page redirection to land your users on the appropriate page 3. Etc..
  • 63.  Auto redirect a page <body onload="window.location='www.google.com';">  Auto redirect a page after sometime <script> function redirect(){ window.location='www.google.com'; } </script> <body onload=“setTimeout(“redirect()“,5000);”> <p>You will be redirected to google.com in 5 seconds. </body>
  • 64.  To redirect visitors onto a different page based on their browser type var browsername=navigator.appName; if( browsername == "Netscape" ) { window.location="http://www.location.com/ns.htm"; } else if ( browsername =="Microsoft Internet Explorer") { window.location="http://www.location.com/ie.htm"; } else { window.location="http://www.location.com/other.htm"; }
  • 65.  The JavaScript print function window.print() prints the current web page when executed  You can call this function directly using the onclick event as shown in the following example  <input type="button" value="Print" onclick="window.print()" />
  • 66.  What are cookies?  are small files which are stored on a user's computer  are designed to hold a modest amount of data specific to a particular client and website  Each cookie is a small lookup table containing pairs of (key, data) values  can be accessed either by a client side or server side script language  Why do we need cookies?  Once a web server is done with sending a web page to a browser, the connection is shut down, and the server forgets everything about the user  Cookies were invented to solve the problem "how to remember information about the user"  How Cookies Work?  When a user visits a web page for the first time, his/her name can be requested and be stored in a cookie.  Next time the user requests the page, cookies belonging to the page is added to the request  This way the server gets the necessary data to "remember" information about users
  • 67.  Cookies are a plain text data record of 5 variable-length fields:  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.  Name: The name of the cookie  Value: The data that is stored on the cookie
  • 68.  JavaScript can create, read, and delete cookies with the document.cookie property.  With JavaScript, a cookie can be created like this: document.cookie="username=John Doe;”  You can also add an expiry date. By default, the cookie is deleted when the browser is closed: document.cookie="username=John Doe; expires=Thu,18 Dec 2013 12:00:00 UTC;”
  • 69.  Read a Cookie with JavaScript  With JavaScript, cookies can be read like this: var x = document.cookie;  document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;  Change a Cookie with JavaScript  With JavaScript, you can change a cookie the same way as you create it:  document.cookie="username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";  Delete a Cookie with JavaScript  Deleting a cookie is very simple. Just set the expires parameter to a passed date:  document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";  Note that you don't have to specify a cookie value when you delete a cookie.
  • 70. <script type="text/javascript"> function WriteCookie(){ if( document.myform.customer.value == "" ){ alert ("Enter some value!"); return; } cookievalue= document.myform.customer.value; document.cookie="name=" + cookievalue; } </script> <body> <form name="myform" action=""> Enter name: <input type="text" name="customer"/> <input type="button" value="Set Cookie" onclick="WriteCookie();"/> </form> </body>
  • 71. <script type="text/javascript"> function ReadCookie(){ var allcookies = document.cookie; // Get all the cookies pairs in an array cookiearray = allcookies.split(';'); // Now take key value pair out of this array for(var i=0; i<cookiearray.length; i++){ name = cookiearray[i].split('=')[0]; value = cookiearray[i].split('=')[1]; document.write ("Key is : " + name + " and Value is : " + value); } } </script><body> <form name="myform" action=""> <p> click the following button and see the result:</p> <input type="button" value="Get Cookie" onclick="ReadCookie()"/> </form></body>