Unit - 3 JavaScript
Unit - 3 JavaScript
» Advantages:
• The Web browser uses it’s own resources, and remove the
burden on the server.
» Disadvantages:
• A JavaScript program can either be placed directly in a Web page file or saved
in an external text file
• Use the <script> tag (also use the type attribute to define the scripting
language).
<html>
<head>
<script type="text/javascript">
</script>
</head>
<body>
</body>
</html>
Inserting JavaScript into a Web Page
• A JavaScript program can either be placed directly in a web page file or saved in
an external text file.
• Use the <script> tag (also use the type attribute to define the scripting
language). Example: Include JS program directly in a web page.
<html>
<head>
<script type="text/javascript">
</script>
</head>
<body>
</body>
</html>
Inserting JavaScript into a Web Page
• Scripts can be provided locally or remotely accessible JavaScript file using src
attribute.
• A variable declared within a JavaScript function becomes LOCAL and can only
be accessed within that function. (the variable has local scope).
• Variables declared outside a function become GLOBAL, and all functions on the
web page can access it.
<!DOCTYPE html>
<head>
<title>Title</title>
</head>
<body>
<script type="text/javascript">
alert("Page is loaded...");
</script>
</body>
</html>
Creating JavaScript Functions
• Functions can be defined both in the <head> and in the <body> section of a
document.
<head>
<script type="text/javascript">
function displaymessage()
{
alert("My first Java Script Program");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form> </body>
Creating JavaScript Functions Example
Working with Conditional Statements
• Conditional statements are commands that run only when specific condition(s)
are met. (If then else then) - Example
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
Working with Program Loops
• Alert Box:
– An alert box is often used if you want to make sure information comes
through to the user.
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()" value="Show alert box" />
</body>
JavaScript Popup Boxes
• 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.
– If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
box returns false.
JavaScript Popup Boxes
• 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
– Mismatched quotes
– Missing quotes
– Using ( instead of [
– Using = in place of ==
JavaScript Events
Events Event Attributes Meaning Associated
Tags
Blur onblur Losing the focus <button>
<input>
<textarea>
<select>
Change onchange On occurrence of some change <input>
<textarea>
<select>
Click onclick When user click the mouse <a>
button <input>
dbclick ondbclick When user double click the <a>
mouse button <input>
<button>
Keyup onkeyup When user releases the key Form
from the keyboard Element
JavaScript Events
Events Event Attributes Meaning Associated
Tags
Focus onfocus When user acquires the input <input>
focus <select>
<textarea>
Keydown onkeydown When user presses the key Form
down Element
keypress onkeypress When user presses the key Form
Element
mousedown onmousedown When user clicks the left mouse Form
button Element
Mouseup onmouseup When user releases the left Form
mouse button Element
Mousemove onmousemove When user move the mouse Form
Elements
JavaScript Events
Events Event Attributes Meaning Associated
Tags
Mouse out onmouseout when user moves the mouse Form
away from some element Elements
Mouse over onmouseover when the user moves the mouse Form
over some element Elements
Load onload After getting the document <body>
loaded
Reset onreset when the reset button is clicked <form>
Submit onsubmit when the submit button is <form>
clicked
Select onselect On selection <input>
<textarea>
Unload onunload When user exits the document <body>
JavaScript Objects
• Document object:
– When an HTML document is loaded into a web browser, it becomes a
document object.
– The document object is the root node of the HTML document and the
"owner" of all other nodes: (element nodes, text nodes, attribute nodes,
and comment nodes).
– The document object provides properties and methods to access all node
objects, from within JavaScript.
– Tip: The document is a part of the Window object and can be accessed
as window.document.
JavaScript Objects
» Syntax(write):
document.getElementById(“ElementID”).innerHTML = “Content to
Display”;
» Example: document.getElementById(“s1”).innerHTML = “Enter
First Name”;
Forms and Validation
• 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.f1.fn.value;
if (x==null || x=="")
{
alert("First name must be filled out");
document.f1.fn.focus();
return false;
}
}
Forms and Validation
• Validating User:
function validateForm()
{
var myform = document.f1;
if(myform.pass.value==“letmein”)
{
document.write(“Welcome”);
return true;
}
else
{
alert(“Wrong Password”);
myform.pass.focus();
}
}
Forms and Validation
document.form1.pass.focus();
return false;
}
Forms and Validation
return false;
}
Forms and Validation
• Window object:
– window object is JavaScript representation of a browser window.
– window object represents the window or frame that displays the
document and it is the global object in client side programming
– Properties:
• window.open(“URL”, “Windowname”, “Options like height and width”);
• window.close();
• window.defaultStatus = “Statement to display”;
JavaScript Objects
Property Description
availHeight Returns the height of the screen (excluding
the Windows Taskbar)
availWidth Returns the width of the screen (excluding
the Windows Taskbar)
height Returns the total height of the screen
Property Description
host Returns the hostname and port number of a
URL
hostname Returns the hostname of a URL
href Returns the entire URL
origin Returns the protocol, hostname and port
number of a URL
pathname Returns the path name of a URL
port Returns the port number of a URL
protocol Returns the protocol of a URL
search Returns the querystring part of a URL
JavaScript Objects
• Location object Example:
<head>
<script>
function myFunction()
{
var x = location.host;
document.getElementById("demo").innerHTML = x;
}
</script></head><body>
<p>Click the button to display the hostname and port number of the current
URL.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>.
</body>
JavaScript Objects
• Date object:
– Create a date object to store date information. var Today = new Date();
JavaScript Objects
• Math object:
– The Math object is a JavaScript object used for calculations other than
simple math.
Document Object Model (DOM)
• DOM is an API that defines the interface between XHTML and application
program.
• That means, suppose application program is written in JAVA and this java
program wants to access the elements of XHTML web document then it is
possible by using a set of API which belongs to DOM.
Level Description
DOM 0 This model is supported by early browsers. This level could
support JavaScript. This version was implemented in Netscape
3.0 and IE 3.0 browser.
DOM 2 Issued in 2000 that could specify the style sheet. It also
supports the event model with in the document.
• The document in DOM are represented using a tree like structure in which
every element is represented as a node.
– The bottommost nodes that have no children are called leaf nodes.
– The nodes that have the common parent are called siblings.
Document Object Model (DOM)
<html>
<head> Document
<title> First Page </title>
</head>
<head> <body>
<body>
<h1> Hello </h1>
<h2> How are you </h2>
</body>
<title> <h1> <h2>
</html>
First Page Hello How are you
JavaScript Timing Events
◼ To get a timer to work in infinite loop, write a function that calls itself.
JavaScript Timing Events
• setTimeout() Example:
<script type="text/javascript">
function timeMsg()
{
var t=setTimeout("alertMsg()",3000);
}
function alertMsg()
{
alert("Hello");
}
</script>
<body>
<form>
<input type="button" value=“Box in 3 seconds” onclick="timeMsg()" />
</form>
</body>
JavaScript Timing Events
• With Dynamic HTML the emphasis is on making the browser provide a richer
viewing experience through effects like Animation, Filters, Transitions etc.
Dynamic HTML Advantages/Disadvantages
• Advantages:
– No plug-ins required
– Faster web experience (change the page content without load new pages)
• Disadvantages:
• With DOM, we can have a map on every elements in the HTML page.
• With JavaScript, we can access and have operations on the elements in the
DOM tree.
• With Event Handler, we can execute the predefined scripts at any time.
Dynamic HTML Example (Image Viewer)
Dynamic HTML Example (Image Viewer)
<html>
<body>
<img id="imageviewer" title="abc" src="anim0.jpg" 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" onclick="automaticly()">
</form>
</body>
</html>
Dynamic HTML Example (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]="anim4.jpg";
myImages[5]="anim5.jpg";
myImages[6]="anim6.jpg";
myImages[7]="anim7.jpg";
myImages[8]="anim8.jpg";
var imagecounter=myImages.length-1;
var i=0;
Dynamic HTML Example (Image Viewer)
function first()
{
document.getElementById('imageviewer').src=myImages[0];
i=0;
}
function last()
{
document.getElementById('imageviewer').src=myImages[imagecounter];
i=imagecounter;
}
Dynamic HTML Example (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];
}}
Dynamic HTML Example (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>
JavaScript: Introduction to 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. 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.
With JavaScript, you can both create and retrieve cookie values.
JavaScript: Introduction to Cookies
• 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.
document.cookie = "username=GCET";
We can also add an expiry date (in UTC time). By default, the cookie is deleted
when the browser is closed:
With a path parameter, you can tell the browser what path the cookie belongs to.
By default, the cookie belongs to the current page.
var x = document.cookie;
document.cookie will return all cookies in one string much like: cookie1=value;
cookie2=value; cookie3=value;
With JavaScript, you can change a cookie the same way as you create it:
We should define the cookie path to ensure that you delete the right cookie.
Some browsers will not let you delete a cookie if you don't specify the path.
JavaScript: Cookie String
The document.cookie property looks like a normal text string. But it is not.
Even if you write a whole cookie string to document.cookie, when you read it out
again, you can only see the name-value pair of it.
If you set a new cookie, older cookies are not overwritten. The new cookie is added
to document.cookie, so if you read document.cookie again you will get something
like:
If you want to find the value of one specified cookie, you must write a JavaScript
function that searches for the cookie value in the cookie string.
JavaScript: Setting or Storing a Cookie
• The simplest way to create a cookie is to assign a string value to the
document.cookie object, which looks like this:
• For this reason, we have to use the JavaScript escape() function to encode the
value before storing it in the cookie.
Callbacks in Javascript
• A callback is a function passed as an argument to another function
Function Sequence
• JavaScript functions are executed in the sequence they are called. Not in the
sequence they are defined. – Example (Javascript3_callback_fun_sequence)
Sequence Control
• Sometimes you would like to have better control over when to execute a function.
• Suppose you want to do a calculation, and then display the result. – Example
(Javascript3_callback_fun_sequence_control)
• The problem with the example, is that you have to call two functions to display the result.
The problem with the second part of example, is that you cannot prevent the calculator
function from displaying the result. Now it is time to bring in a callback.
Callbacks in Javascript
• A callback is a function passed as an argument to another function.
• Using a callback, you could call the calculator function (myCalculator) with a
callback, and let the calculator function run the callback after the calculation is
finished
Asynchronous JavaScript