ch_5 JS
ch_5 JS
Side Scripting
1
XP
Introduction to JavaScript
2
XP
Introduction to JavaScript
3
XP
Introduction to JavaScript
4
XP
Comparing Java and JavaScript
5
XP
Comparing Java and JavaScript
6
XP
JavaScript Can Do…
7
XP
JavaScript Types:
• Use the <script> tag (also use the type attribute to define the
scripting language)
<html>
<head>
<script type="text/javascript">
</script>
</head>
<body>
</body> 11
</html>
XP
Inserting JavaScript into a Web
Page File
12
XP
Writing Output to the Web Page
document.write(“text”); Or document.writeln(“text”)’
var variable;
variable = value;
17
Working with Expressions andXP
Operators
19
XP
Creating JavaScript Functions
• <html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body> <form>
<input type="button" value="Click me!"
onclick="displaymessage()" />
</form>
</body> 21
</html>
XP
Working with Conditional
Statements
• Comparison operator
• Conditional operator
variablename=(condition)?value1:value2 22
XP
Using Arrays
23
XP
Working with Program Loops
document.write("<br />");
} 25
XP
JavaScript Popup Boxes
Alert Box
• An alert box is often used if you want to make sure information
comes through to the user.
Confirm Box
• A confirm box is often used if you want the user to verify or
accept something.
• When a confirm box pops up, the user will have to click either
"OK" or "Cancel" to proceed.
26
XP
JavaScript Popup Boxes
• If the user clicks "OK", the box returns true. If the user clicks
"Cancel", the box returns false.
Prompt Box
• A prompt box is often used if you want the user to input a value
before entering a page.
• When a prompt box pops up, the user will have to click either
"OK" or "Cancel" to proceed after entering an input value.
• If the user clicks "OK" the box returns the input value. If the user
clicks "Cancel" the box returns null.
27
XP
JavaScript Popup Boxes
}
XP
Debugging Your JavaScript
Programs
31
XP
Common Mistakes
32
XP
JavaScript Events
• 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
33
• A keystroke
XP
JavaScript Events
36
XP
JavaScript Events
• The onload and onUnload events are triggered when the user
enters or leaves the page
• Both the onload and onUnload eThe 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
• vents are also often used to deal with cookies that should be
set when a user enters or leaves a page.
37
XP
JavaScript Events
id="email" onchange="checkEmail()">;
38
XP
JavaScript Events
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()">
39
</body> </html>
XP
JavaScript Events
onSubmit
• The onSubmit event is used to validate all form fields before
submitting it.
<html> <head>
<script type="text/javascript">
function validate()
{
// return true or false based on validation logic
}
</script> </head>
<body>
<form name=“f1” action="tryjs_submitpage.htm" onsubmit="validate()">
toUpperCase() method
<script type="text/javascript">
document.write(txt.length)
document.write(txt.toUpperCase())
</script>
String , Date , Array , Boolean and Math are Built in javascript objects.
45
XP
JavaScript Object
Properties
• Object properties are defined by using the object's name and the
property name.
46
XP
JavaScript Object
Method
To invoke method
myobject.method();
myobject.method(x,y,z);
Exa.
Today.getDay();
47
XP
The document object
document.bgcolor=red
document.linkcolor=yellow
Example
<form name=“userdetails”>
</form>
document.formname
document.userdetails.fname.value
XP
Window object
• 50
XP
open:
window.open()
open("URLname","Windowname",["options"])
51
XP
<!DOCTYPE html>
<html>
<head>
<script>
function openWin()
{
myWindow=window.open("",”","width=200,height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
}
function closeWin()
{
myWindow.close();
}
</script>
</head>
<body>
<input type="button" value="Open 'myWindow'" onclick="openWin()" />
<input type="button" value="Close 'myWindow'" onclick="closeWin()" />
52
</body>
</html>
XP
frames
navigator
location
history
document
screen
• frames: The frames property returns an array of all the frames
(including iframes) in the current window.
53
XP
NAVIGATOR OBJECT
<html>
<body>
<script type="text/javascript">
document.write("Browser Name is: " + navigator.appName);
document.write("<br>Browser Code is: " + navigator.appCodeName);
document.write("<br>Browser Version No is: " + navigator.appVersion);
document.write("<br>Platform is: " + navigator.platform);
document.write("<br>User agent Header: " + navigator.userAgent);
document.write("<br>Cookies Enabled is: " + navigator.cookieEnabled);
</script>
</body>
</html>
55
XP
Tutorial 10 56
XP
SCREEN OBJECT
• screen : it will give information about size of user’s display and color
depth.
Property Description
Returns the height of the screen
availHeight
(excluding the Windows Taskbar)
Returns the width of the screen
availWidth
(excluding the Windows Taskbar)
Returns the bit depth of the color palette
colorDepth
for displaying images
height Returns the total height of the screen
Returns the color resolution (in bits per
pixelDepth
pixel) of the screen
57
width Returns the total width of the screen
XP
Location Object
• The location object is part of the window object and is accessed through the
window.location property.
• This differs from the document object because the document is the real
content; the location is simply the URL.
• URL consists of many components that define the address and method of
data transfer for a file.
• Pieces of a URL include the protocol (such as http:) and the hostname (such
as www.giantco.com).
• Setting the location.href property is the primary way your scripts navigate to
other pages: location.href = “http://www.dannyg.com” 58
XP
Location Object
Property Description
Returns the hostname and port of a
host
URL
hostname Returns the hostname of a URL
href Returns the entire URL
pathname Returns the path name of a URL
Returns the port number the server
port
uses for a URL
protocol Returns the protocol of a URL
• The history object contains the URLs visited by the user (within a
browser window).
• Each window maintains a list of recent pages that the browser has
visited.
• While the history object’s list contains the URLs of recently visited
pages, those URLs are not generally accessible by script due to
privacy and security limits imposed by browsers.
Property Description
Returns the number of
length
URLs in the history list
Method Description
Loads the previous URL in
back()
the history list
Loads the next URL in the
forward()
history list
Loads a specific URL from
go()
the history list
61
XP
History Object
• <html>
<head>
<script>
function goBack()
{
window.history.go(-2);
}
</script>
</head>
<body>
<input type="button" value="Go back 2 pages" onclick="goBack()">
</body>
</html> 62
XP
The Link Object
• A link object is the object model equivalent of an <A> tag when the tag
includes an HREF attribute.
• When you want to click a link to execute a script rather than navigate directly
to another URL, you can redirect the HREF attribute to call a script function.
• If you place the name of a function after the javascript: URL, then a
scriptable browser runs that function.
63
XP
The Link Object
• <A HREF=”javascript:void”
onClick=“functionName([parameter1]..[parameterN])”> </A>
• The void keyword prevents the link from trying to display any value
that the function may return.
64
XP
DOM & Web Browser Environment
65
XP
DOM History and Levels
4. The bottommost nodes that have no children are called leaf nodes.
5. The nodes that have the common parent are called siblings.
67
XP
DOM Tree
<html>
Document
<head>
<body>
• Required Fields
The function below checks if a field has been left empty. If the
field is blank, an alert box alerts a message, the function returns
false, and the form will not be submitted:
function validateForm()
{
var x=document.form1.fname.value;
if (x==null || x=="")
{
alert("First name must be filled out");
document.form1.fname.focus();
return false;
}
69
}
XP
Forms And Validation
• Validating User:
function f1()
{
var myform = document.f1;
if(myform.pass.value==“letmein”)
{
document.write(“Welcome”);
returm true;
}
else
{
alert(“Wrong Password”);
myform.pass.focus(); 70
}}
XP
Forms And Validation
71
XP
Forms And Validation
E-mail Validation
• The function below checks if the content has the general syntax of an
email.
• This means that the input data must contain an @ sign and at least
one dot (.). Also, the @ must not be the first character of the email
address, and the last dot must be present after the @ sign, and
minimum 2 characters before the end
function validateForm()
{ abc_123@yahoo.co.in
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>x.length)
{
alert("Not a valid e-mail address"); 72
return false; } }
XP
Forms And Validation
function f1(){
var check=document.form1.email.value;
Document.write(testmail(check));
function testmail(chkmail){
var emailpattern=“^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$”;
}
73
XP
Forms And Validation
This sequence begin with ^. Means check the first character is a word
represented by \\w. it can be also _, - which normally not used but are legal.
The * means that the next series of characters described can be repeated many
times of not at all.
This section begin with @ character. Followed by word character and then at
least one dot (.).
Text-related objects
field.value = “abc”
75
<INPUT TYPE=”text” NAME=”converter” VALUE=”sample”>
XP
Forms And Validation
function f1()
document.form1.pass.focus();
return false;
78
}}
XP
Forms And Validation
function validate() {
var mobile = document.getElementById("mobile").value;
var pattern = “/^\d{10}$/”;
if (pattern.test(mobile)) {
alert("Your mobile number : "+mobile);
return true;
}
alert("It is not valid mobile number.input 10 digits number!");
return false; 79
}
XP
Forms And Validation
if(document.form1.fname.value.match(alphaExp))
return true;
else{
document.form1.fname.focus();
80
return false;}}
XP
Forms And Validation
– document.form1.selectName.value
81
XP
Forms And Validation
<script language="javascript">
function f1(f_o){
</script>
<form name="form1">
String Functions
Concatnation
var msg = “Four score” + “ and seven”
Changing string case
var result = string.toUpperCase()
var result = string.toLowerCase()
String searches
indexOf() function returns the position of a character in a string.
Strpos=stringname.indexOf(“@”);
which Char=stringName.charAt(index)
Example :
var stringA = “Building C”
• var bldgLetter = stringA.charAt(9) // result: bldgLetter = “C” 84
XP
Forms And Validation
<html> <head>
<script type="text/javascript">
function timeMsg()
{
var t=setTimeout("alertMsg()",3000);
}
function alertMsg()
{
alert("Hello");
}
</script> </head>
<body> <form>
<input type="button" value="Display alert box in 3 seconds"
onclick="timeMsg()" />
</form> </body>
87
</html>
XP
Timing Event
Timing Event
90
XP
Timing Event
95
XP
Cookies
• Web Browser and Server use HTTP protocol to communicate and HTTP is a
stateless protocol. But for a commercial website it is required to maintain
session information among different pages. For example one user registration
ends after completing many pages. But how to maintain user's session
information across all the web pages.
• A cookie is a variable that is stored on the visitor's computer. Each time the
same computer requests a page with a browser, it will send the cookie too.
96
With JavaScript, you can both create and retrieve cookie values.
XP
How It Works ?
• Your server sends some data to the visitor's browser in the form of a
cookie. The browser may accept the cookie. If it does, it is stored as a
plain text record on the visitor's hard drive.
• Now, when the visitor arrives at another page on your site, the
browser sends the same cookie to the server for retrieval.
97
XP
Types
98
XP
Cookie Variables
100
XP
Setting or Storing a Cookie
window.document.cookie =
“cookieName = cookieValue; expires = expireDate;
path = pathName; domain = domainName; secure”;
101
XP
Setting or Storing a Cookie
<script type="text/javascript">
function WriteCookie()
{
if( document.myform.customer.value == "" )
{
alert("Enter some value!");
return;
}
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
alert("Setting Cookies : " + "name=" + cookievalue );
}
</script> 102
XP
Setting or Storing a Cookie
For this reason, we have to use the JavaScript escape() function to encode the
value before storing it in the cookie.
103
XP
DHTML (Image Viewer)
<body>
<center>
<img id="imageviewer" title="abc" src="anim0.jpg" alt="w3Scools"
width="200" height="100" />
<form name="form1">
<input name="First" type="button" value="First" onclick="first()">
<input name="Previous" type="button" value="Previous"
onclick="previous()">
<input name="Next" type="button" value="Next" onclick="next()">
<input name="Last" type="button" value="Last" onclick="last()">
</br>
<input type="checkbox" name="automatic" value="Automatic"
onClick="automaticly()">
104
</form></center></body></html>
XP
DHTML (Image Viewer)
105
XP
DHTML (Image Viewer)
<script type="text/javascript">
var myImages=new Array();
myImages[0]="anim0.jpg";
myImages[1]="anim1.jpg";
myImages[2]="anim2.jpg";
myImages[3]="anim3.jpg";
myImages[4]="Desert.jpg";
myImages[5]="Jellyfish.jpg";
myImages[6]="Koala.jpg";
myImages[7]="Penguins.jpg";
myImages[8]="Waterfall.jpg";
var i=0;
XP
DHTML (Image Viewer)
function first()
{
document.getElementById('imageviewer').src=myImages[0];
i=0;
}
function last()
{
document.getElementById('imageviewer').src=myImages[imagecounter];
i=imagecounter;
}
107
XP
DHTML (Image Viewer)
function next()
{
if (i<imagecounter)
{
i++;
document.getElementById('imageviewer').src=myImages[i];
}}
function previous()
{
if (i>0)
{
i--;
document.getElementById('imageviewer').src=myImages[i]; 108
}}
XP
DHTML (Image Viewer)
function automaticly()
{
if (document.form1.automatic.checked)
{
if (i<myImages.length)
{
document.getElementById('imageviewer').src=myImages[i];
i++;
var delay = setTimeout("automaticly()",1500);
}
}
}
</script> 109