CH - 5 JS
CH - 5 JS
Side Scripting
1
Introduction to JavaScript
2
Introduction to JavaScript
3
Introduction to JavaScript
4
Comparing Java and JavaScript
5
Comparing Java and JavaScript
6
JavaScript Can Do…
7
JavaScript Types:
12
Writing Output to the Web Page
document.write(“text”); Or document.writeln(“text”)’
var variable;
variable = value;
17
Working with Expressions and
Operators
19
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>
Working with Conditional
Statements
variablename=(condition)?value1:value2 22
Using Arrays
23
Working with Program Loops
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
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.
JavaScript Popup Boxes
}
Debugging Your JavaScript
Programs
31
Common Mistakes
32
JavaScript Events
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
•
JavaScript Events
36
JavaScript Events
id="email" onchange="checkEmail()">;
38
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>
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
Name (max 10 chararcters): <input type="text" id="fname" size="20"><br />
" onsubmit="validate()">
Age (from 1 to 100): <input type="text" id="age" size="20"><br />
E-mail: <input type="text" id="email" size="20"><br /> <br />
<input type="submit" value="Submit">
41
</form> </body> </html>
JavaScript Events
toUpperCase() method
<script type="text/javascript">
var txt="Hello
World!“
document.write(txt.length)
document.write(txt.toUpperCase())
</script>
String , Date , Array , Boolean and Math are Built in javascript
JavaScript Object
Properties
• Properties are object attributes.
• Object properties are defined by using the object's name and the
property name.
46
JavaScript Object
Method
To invoke method
myobject.method();
myobject.method(x,y,z);
Exa.
window document.bgcolor=red
document.linkcolor=yellow
<form name=“userdetails”>
</form>
document.formname
it can be referred by
document.userdetails
49
any element within it can accessed by
Window object
open(“http://google.com”, “My
Google”,”height,width”);
51
<!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'" 52
onclick="closeWin()" />
frames
navigator
location
history
document
screen
• frames: The frames property returns an array of all the
frames (including iframes) in the current window.
53
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
• Browser Name is: Netscape
Browser Code is: Mozilla
Browser Version No is: 5.0 (Windows NT 6.3; Win64;
x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/55.0.2883.87 Safari/537.36
Platform is: Win32
User agent Header: Mozilla/5.0 (Windows NT 6.3;
Win64; x64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/55.0.2883.87 Safari/537.36
Cookies Enabled is: true
Tutorial 10 56
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
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.
• Methods of the history object allow for navigating backward and
forward through the history relative to the currently loaded page.
60
History Object
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
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
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.
• The technique called as javascript: URL.
• If you place the name of a function after the javascript: URL,
then a scriptable browser runs that function.
63
The Link Object
64
DOM & Web Browser Environment
65
DOM History and Levels
66
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
}
Forms And Validation
• Validating User:
function f1()
{
var myform = document.f1;
if(myform.pass.value==“l
etmein”)
{
document.write(“Welcome”);
returm true;
}
else
{
alert(“Wr 70
ong
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()
{ [email protected]
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)
{ 72
return false;
alert("Not } }e-mail
a valid
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
Forms And Validation
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 (.).
74
The last
There arepart
someis:character
[\\w]+[\\w]$
after last dot (.).
Forms And Validation
Text-related objects
• Four text-related HTML form elements—text, password and
field.value = “abc”
75
<INPUT TYPE=”text” NAME=”converter” VALUE=”sample”>
Forms And Validation
function f1()
document.form1.pass.focus();
return false;
78
}}
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
}
Forms And Validation
if(document.form1.fname.value.match(alphaExp))
return true;
else{
document.form1.fname.focus();
80
return false;}}
Forms And Validation
– document.form1.selectName.value
<script
language="javascript">
function f1(f_o){
</script>
<form name="form1">
<input type="radio"
<input type="radio" name="group1" onclick=f1(this)>
name="group1" 83
value="Blue"
value="Red" Blue </br> </form>
Forms And Validation
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
(“@”); 84
which
Forms And Validation
<html> <head>
<script type="text/javascript">
function timeMsg()
{
var
t=setTimeout("alertMsg()",30
00);
}
function alertMsg()
{
alert("Hello");
}
</script> </head>
<body> <form>
</form> </
<input type="button" value="Display alert box in 3 87
body>
seconds" onclick="timeMsg()" />
Timing Event
90
Timing Event
} } </html>
Event, Attributes & Tags
95
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.
• In many situations, using cookies is the most efficient method of
remembering and tracking preferences, purchases, commissions, and other
information required for better visitor experience or site statistics.
• 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.
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.
• Once retrieved, your server knows/remembers what was
stored
earlier.
97
Types
98
Cookie Variables
100
Setting or Storing a Cookie
window.document.cookie =
“cookieName = cookieValue; expires = expireDate;
path = pathName; domain = domainName;
secure”;
101
Setting or Storing a Cookie
<script type="text/javascript">
function WriteCookie()
{
i
f
(
d
o
c
u
m
e
n
t 102
.
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
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
>
DHTML (Image Viewer)
105
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;
DHTML (Image Viewer)
function first()
{
document.getElementById('imageviewer').src=myImages[0];
i=0;
}
function last()
{
document.getElementById('imageviewer').src=myImages[im
agecounter];
i=imagecounter;
}
107
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
}}
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