Section-2 WEB DESIGN
Section-2 WEB DESIGN
1. Introduction
2. Objectives
3. Session 1: Preliminaries
4. Session 2: HTML Forms
5. Session 3: CSS
6. Session 4: JavaScript HTML DOM
a. Introduction
b. DOM methods and properties
c. DOM programming interface
7. Session 5: JavaScript HTML DOM
a. DOM Events
b. HTML DOM event listener
8. Session 6: JavaScript HTML DOM
a. DOM navigation
b. HTML DOM elements
9. Session 7: JavaScript Error Handling
10. Session 8: JavaScript Classes
11. Session 9: JavaScript Async
12. Session 10: JavaScript Cookies
Introduction
The lab manual contains ten sessions. The first two sessions cover the basic concepts
on HTML forms and CSS. Then, you will be redirected to learn the advanced
JavaScript concepts. Each session introduces the topics & with examples. Some
programming exercises are provided for the hands-on practise. From session 3
onwards, you will be able to learn the advanced JavaScript concepts like HTML
DOM, error handling, object-oriented programming, cookies, and JSON.
6
Objectives Web
Web Design
DesignLab
Lab
Session 1: Preliminaries
1.0 Introduction
JavaScript has nothing to do with Java, is dynamically typed and has C-like syntax.
JavaScript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side
script to interact with the user and make dynamic pages. It is an interpreted
programming language with object-oriented capabilities. In this session we will
introduce the basic JavaScript constructs, conditional statement and control flow
statements.
1.1 Objectives
JavaScript can be included in html in two ways: Internal and external file.
<script>
x = 3;
</script>
<head>
</head>
OR
<head>
7
DAA & Web Design Lab <script src="http://example.com/script.js"></script>
</head>
Javascript provides conditional statements i.e. if. . . else, nested if. . . .else and switch.
. .case. Following are the syntax of conditional statements in Javascript:
if. . . else
Syntax:
if (condition1)
{
// statements to be executed if condition1 is true
} else if (condition2) {
// statements to be executed if the condition1 is false and condition2 is true
} else
{
// block of code to be executed if both condition1 and condition2 are false
Example 1
if (str == "Hello")
{ // if-else
alert("Hi"); // popup dialog
}
else
{
alert("something is wrong!");
}
Output:
Based on the value of str, popoup dialog box will be shown.
switch. . . . case
Syntax:
switch(expression)
{
case p:
// code block
break;
case q:
// code block
break;
default:
// code block
}
8
Example 2 Web
Web Design
DesignLab
Lab
switch (name)
{ // switch statement
case "Bob":
alert("Hi Bob!")
break
case "Joe":
alert("Hey Joe.")
break
default: alert("Do I know you?")
}
Output:
Based on the value of the variable name, the corresponding case statement
will be executed, if none of the case is true, the default case will be executed.
Loops
Loops are used to execute certain statements multiple number of times. In javascript
while and for loops are available to use.
while loop:
Syntax:
while (condition)
{
// statements to be executed if condition is true
}
Example:
while (i<n)
{ // the basics
// do something
i++;
}
Output:
T c d b c d c d
the condition i<n, is true.
for loop:
Syntax:
Where,
Example 3
Output:
Here,
2. i<n is executed,
Now, 2nd cycle is executed until the condition meets false value.
Similar to other programming languages, javascript also enables the use of functions.
Functions are the code block written to meet a specific task.
Syntax:
{
// function code block to be executed
}
Example 4
function foo(x,y)
10
{ Web
Web Design
DesignLab
Lab
//function code block to be executed
return x*y;
1.5 Exercises
1. Write a JavaScript code to perform the two-digit arithmetic operations: Addition,
Subtraction, Multiplication and Division.
2. Write a JavaScript code to print 1 for 1 time, 2 for 2 times, 3 for 3 times and so on
upto 10.
3. Design a web page that describes you. Your page must include following details
(extra details and creativity are welcome):
2.0 Introduction
This session provides basic understanding of creating and using the HTML form. We
will learn, how to use Form elements in HTML to collect the information from user
such as input, text field, label, radio button, text area, submit button etc. It would be
desired to practise all the examples during the session as well as exercises.
2.1 Objectives
1. The <form> Element:To make a dynamic HTML webpage, in real time user inputs
are required. In HTML, the element <form> is used trough which user inputs are
acquired.
The format of <form> element is as follows:
<form>
.
form elements
.
</form>
User inputs can be acquired in many forms like: submit button, text, radio button,
checkbox etc. Some of them are describe below:
type="text"
It creates a text field, used to acquire user input in the form of text.
Example:
<form>
<input type="text" id="lname" name="lname">
</form>
type="radio"
It creates radio button, used to acquire the user selection choice. Radio buttons are
used for selecting one out of many options.
Example:
<p>Choose an option:</p>
<form>
<input type="radio" id="opt1" name="opt" value="Option1">
<label for="opt1">Option1</label><br>
<input type="radio" id="opt2" name="opt" value="Option2">
<label for="opt2">Option2</label><br>
12
<input type="radio" id="opt3" name="opt" value="Option3"> Web
Web Design
DesignLab
Lab
<label for="opt3">JavaScript</label>
</form>
type="checkbox"
It creates checkbox used to acquire the user choices. checkboxes are used for selecting
none or more than one choice.
Example:
<form>
<input type="chkbox" id="car1" name="car1" value="Maruti">
<label for="car1"> I own a Maruti Car</label><br>
<input type="chkbox" id="Car2" name="Car2" value="Hyundai">
<label for="Car2"> I own a Hyundai Car</label><br>
<input type="chkbox" id="Car3" name="Car3" value="F d >
<label for="Car3"> I Own a Ford Car</label>
</form>
type="submit"
It creates a submit button, which can be used to submit the form.
Example:
<form action="/actions.php">
<label for="f_name">First name:</label><br>
<input type="text" id="f_name" name="f_name" value="John"><br>
<label for="l_name">Last name:</label><br>
<input type="text" id="l_name" name="l_name" value="Li"><br><br>
<input type="submit" value="Submit">
</form>
type="button"
It creates a clickable button.
type="email"
In HTML5 new input field to acquire Email address from user was introduced.
Syntax:
<input type="email">
Example:
<form>
<input type="email">
<input type="submit" value="Submit">
</form>
To allow multiple Email Ids at once, use following syntax:
<input type="email" multiple>
While entering multiple Email Ids use , to separate each other.
type="search"
Whether it is Google, social sites or e-commerce sites, searching for desired content is
what most of the user perform today. HTML5 provides a search field to use in your website.
Example:
<form >
13
DAA & Web Design Lab <input type="search" name="search">
</form>
type="url"
Like Email field HTML5 also provide the url field to acquire web addresses. Browser
also performs simple validation to check the syntax correctness of the url entered.
Syntax:
< =" " a = >
type = da
Upto HTML4, the date pickers were to be constructed with JavaScript libraries. HTML5
enables this functionality possible within the browser.
To show the calendar, following syntax can be used:
<input type = da d="d b" a ="d b">
To show the month and year only:
< = d=" " a =" " d>
To show the time only:
< = d=" " a =" ">
Note: The name attribute in <input> element is very important. The value stored in the
input element will not be sent if the name attribute is missing.
2.3 Exercises
1. Create an HTML webpage, as shown in figure. The user can specify any expression
as input. Use form element to collect the user data.
2. Create a scrolling list that shows five items from the following list of PC processors:
Intel i7, Motorola 68000, AMD Athlon , Intel 8088, AMD Ryzon, Intel Pentium MMX,
Intel i3, Intel Pentium II, Intel Pentium III, Intel i5, Intel Celeron, PowerPC G3, PowerPC
G4,.
3. Design a webpage for a software company to accept on-line job applications. The
webpage must be designed to use form with elements:
Position applied for (autofocus), name, nationality, date of birth (selected from an
auto picker), address (in a text area), telephone number and email (required).
Educational history and qualifications.
14
Work experience/employment/training in terms of employer history and number Web
Web Design
DesignLab
Lab
of years of experience selected from a slider. Set maximum years of experience
to 10 years.
Personal statement.
Two referees including names, occupation, relationship, address, telephone.
3.0 Introduction
Web pages belong to the same website, each page should have a consistent look in
order to provide familiarity for the user. Style sheets are used in desktop publishing to
provide consistency when formatting text. When a big project containing large
number of web pages and elements, is handled by a team of web developers, requires
extra efforts to maintain similar design and style among all the developers. To make
this task easy, CSS is used to style and layout web pages. Using CSS, style attributes
of HTML elements such as: font, color, size, and spacing of your content, split it into
multiple columns, or add animations and other decorative features can be set.
This session is a recap session for CSS covering the basics of how it works, what the
syntax looks like, and how you can start using it to add styling to HTML.
3.1 Objectives
15
DAA & Web Design Lab 3.2.1 Internal CSS:
Internal CSS is included within the <head> element. It can be used to style a single
HTML page only. It is accessible to all the elements of that HTML document i.e. it is
globally defined in the HTML file.
Syntax:
<style>
HTML_tag
{
style attributes
}
</style>
Example:
<html>
<head>
<style>
body
{
background-color: green;
}
h1
{
margin-left: 20px;
color: red;
}
</style>
</head>
<body>
Inline CSS is specific to the element. It is included within the element to which it has
to be applied. It is element specific style design.
Syntax:
<HTML_Tag style="style_attributes">Content of Tag</HTML_Tag>
Example:
<html>
<body>
External CSS is written in a file with extension .css and can be included in any HTML
page as desired to be style with it. For website with many web pages, it is very easy to
maintain and modify the style and design of the whole website using external style
sheet, by just updating the one file: CSS. Each HTML page must include a reference
to the external style sheet file inside the <link> element, inside the head section.
Syntax:
<link rel="stylesheet" href="external_css.css">
This should be included within <head> tag.
Example:
<html>
<head>
<link rel="stylesheet" href="external_css.css">
</head>
<body>
</body>
</html>
The external_css.css file looks like this:
body
{
background-color: lightblue;
}
h2
{
color: navy;
margin-left: 20px;
}
Here, in this body and h2 are the HTML elements for which style attributes are
defined in this CSS file.
When multiple styles are available to a web page, all of them will "cascade" into a
new "virtual" style sheet by the virtue of the following rules, with first one having the
highest priority:
1. Inline style
2. External and internal style sheets
3. Browser default
That is, an inline style has the highest priority, and will override all other three styles.
17
DAA & Web Design Lab 3.4 Exercises
1. Create an HTML website to display the time table of all the 4 years of B. Tech.
( ac a ). I dc a a a ac a
time table is listed. On click to any year time table a new web page should be open
displaying the corresponding time table. Apply the following effects on the table using
CSS:
- Common to all:
o Display day names (Mon, Tue etc...) in bold format with the first
letter in the dayname in uppercase.
o Display lunch slightly in bigger font other than the remaining text.
- Specific to each year:
o For 1st year
o Apply blue as the background colour and white for the colour of
the text in the table header.
o For 2nd year
o Apply green as the background colour and white for the colour of
the text in the table header.
o For 3rd year
o Apply purple as the background colour and white for the colour
of the text in the table header.
o For 4th year
o Apply yellow as the background colour and black for the colour
of the text in the table header.
2. Create an HTML webpage to show personal information i.e. name, class,
qualifications, photo,address etc. Make use of tables as when possible. Apply the
following styleinformation using CSS:
- Display the heading of the page in Arial font and with font size of
18px.
- Align all the field names like Name, Class, Photo etc to left in the
table.
- Apply yellow color as background colour in left side cells contains
field names like Name, Class etc...
- Set college logo as background image to the web page.
4.0 Introduction
HTML DOM stands for Hyper Text Markup Language Document Object Model.
When a browser loads an html page, it creates a DOM of this html page. HTML DOM
provides ability to JavaScript to access and modify any element of an HTML
document.
HTML DOM is constructed in the form of a tree to show the parent-child relationship
of various elements of the HTML page.
HTML DOM considers:
The entire document as a document node
Each HTML element as element node
Text content within an HTML element as text nodes
Comments as comment nodes
Below is an example of HTML DOM for the shown HTML page.
code 1:
<html>
<head>
<title>My Title></title>
<body>
19
DAA & Web Design Lab
Text: "My Title"
Element:
Element: <title>
<head>
Element:
Element: <p> Element: <h1>
<body>
Comment: "This
is comment" Text: "My First
Heading"
From the above HTML code and figure, we can read as:
<html> is the root node of the page and is the parent node
of <head> and <body>
<head> is the first child of <html>
<body> is the last child of <html>
<head> has a child node: <title>
<title> has a child (a text node): "DOM Tutorial"
<body> has two children: <h1> and <p>
<h1> has one child (a text node): "DOM Lesson one"
<p> has one child: "Hello world!"
<h1> and <p> are siblings
The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.Following are the capabilities of JavaScript with HTML DOM. It can:
add new HTML element or attributes of an element in the html page.
modify any of the HTML elements or attributes of an element in the html
page.
modify a CSS style in the html page
remove any of the HTML elements or attributes of an element in the html
page.
react to any of the existing HTML events in the html page.
add new HTML events in the html page.
JavaScript objects consist of properties and methods. When a web browser renders an
HTML document, it creates a DOM of HTML document. As we know in DOM every
HTML element is treated as a JavaScript Object which has a number of method and
properties associated with it.
HTML DOM Methods: They are the actions could be performed on Elements of
HTML page.
20
HTML DOM properties: These are the values or attributes Elements of HTML page Web
Web Design
DesignLab
Lab
that could be set or updated.
The DOM programming interface is the actions or methods and values or properties of
an object/HTML Element.
As discussed above the property of an object is a value that can be get or set i.e.
updating the content of an HTML element.To update an HTML element, first we need
to access it by finding that particular element in the whole document or the web
page.As we have already learned the methods to access or find an HTML element in
the HTML course, an element can be accessed by its ID, Tag Name or by the Class
Name. Out of these thewidely used method is accessing the element by its ID i.e.
document.getElementById(id)
Property Description
Method Description
21
DAA & Web Design Lab the element: document.
Method Description
Explanation:
22
{ Web
Web Design
DesignLab
Lab
document.getElementById("para1").innerHTML = "The text is changed";
}
</script>
</body>
</html>
Explanation:
The id of an element is used to access an HTML element. Here, the method
getElementById is used to find the element with id="para1".
Following syntax is used to change the style of an HTML element using HTML
DOM:
document.getElementById(element_id).style.property = new style
Example:
Changing the color of content of the element: h2 using HTML DOM.
<!DOCTYPE html>
<html>
<head>
<title>Style change</title>
</head>
<body>
</body>
</html>
Result: As shown below the color of the content of h2 element is changed from red to
green.
23
DAA & Web Design Lab
4.3 Exercises
1. Design an HTML page using JavaScript as shown below. When Try button is
pressed, the Full Name should be shown below the Try button. (Hint: Use
concatenation to get Full Name.
On Click on Try:
2. Modify the below snippet of the code to change the src attribute of the image
. HTML DOM.
<img id="pic" src="old.jpg">
<script>
//Write your code here.
</script>
24
Web
Web Design
DesignLab
Lab
3. Write the JavaScript code to change the color of the HTML element h2 to green, on
c c c a c b .
5.0 Introduction
5.1 Objectives
Example 1: Write a javascript code to change the contents of an element like header
tag or paragraph tag or a division tag etc when user clicks on it.
Solution:
<!DOCTYPE html>
<html>
<head>
<title> DOM Events</title>
</head>
<body>
<p id="para1", onclick="abc()">Click here</p>
<script>
function abc()
{
para1.innerHTML = "This is changed text after click";
}
25
DAA & Web Design Lab </script>
</body>
</html>
Result: Before click:
After click:
Event Listeners are attached to elements and fired when certain event
occurs.addEventListener() is a method which is used to attach an event handler to an
element. This method adds an event handler in addition to the existing ones i.e.
existing event handlers are not overwritten. In this manner more than one event
handlers (even of the same type) can be attached to one element.
When using the addEventListener() method, the JavaScript is separated from the
HTML markup, for better readability and allows you to add event listeners even when
you do not control the HTML markup.
Similarly, an existing event handler to an element can be removed using the
method: removeEventListener().
Syntax
element.addEventListener(event, function, useCapture);
Where,
event: is the type of the event
function: in this the actions to be performed on event are defined.
useCapture: it is a Boolean value and is optional field. it is used to specify whether to
use event bubbling or event capturing.
26
Web
Web Design
DesignLab
Lab
They specify the order of event propagation in the HTML DOM. Consider following
snippet of HTML page:
<div>
<p>
</p>
</div>
Both the elements: div and p are implemented with event handlers.
What will be the order of execution of events, if <p> element is clicked 1st?
In bubbling the inner most element's event is handled 1st a d
event i.e. the event of <p> element is handled 1st and then the event of <div> element.
To use bubbling method, the value of useCapture is passed as Boolean False.
In capturing the outer most element's event is handled 1stand then the inner
event i.e. the event of<div> element handled 1st and then the event associated with
<p> element. To use capturing method, the value of useCapture is passed as Boolean
True.
By defaultbubbling propagation is used i.e. useCapture is set to false.
Example2
Add an event handler to the element button, where onclick an alert message is shown.
Solution:
<!DOCTYPE html>
<html>
<head>
<title>Add Event Listener</title>
</head>
<body>
<h3>JavaScript HTML DOM addEventListener()</h3>
<p>Click on submit button below to which addEventListener() method is associated
and shows an alert message on button click.</p>
<button id="btn1">Submit</button>
<script>
document.getElementById("btn1").addEventListener("click", abc);
function abc() {
alert ("Event handler!");
}
</script>
</body>
</html>
Example 3
Add two click events to the element: button, where in first clickan alert message T
c c is shown a d c dc c a a a T c dc c
shown.
Solution:
27
DAA & Web Design Lab <!DOCTYPE html>
<html>
<head>
<title>Adding Multiple Event Listener to an Element</title>
</head>
<body>
<h3> Adding Multiple Event Listener to an Element </h3>
<p>Click on submit button below to which to see the effect of multiple event listeners
added to an element.</p>
<button id="btn1">Submit</button>
<script>
document.getElementById("btn1").addEventListener("click", abc1);
document.getElementById("btn1").addEventListener("click", abc2);
function abc1()
{
alert ("This is first click");
}
function abc2()
{
alert ("This is second click");
}
</script>
</body>
</html>
5.3 Exercises
1. D a HTML a a b .I O b c c
display the da HTML DOM .
Before click on submit button:
28
Web
Web Design
DesignLab
Lab
2. Design an HTML page to shown that, when this page is loaded it must check the
c a b a dd a a a acc d box
. . c a ab d : C a ab d a d :
C a d ab d . I O ad HTML DOM .
3.Whenever user input a text in the text box in any case (i.e. upper or lower case),
automatically it should be converted to uppercase. Design an HTML page to
ab c a HTML DOM C a .
6.0 Introduction
As discussed earlier in the Introduction section, the HTML DOM interprets the
HTML page as the nodes with respect to the elements. These nodes can be navigated
with the help of the node tree using node relationships.
6.1 Objectives
29
DAA & Web Design Lab 6.2
An HTML element is created 1st and then appended before or after to an existing
element.
30
The following syntax is used to create a new HTML element: Web
Web Design
DesignLab
Lab
var new_element = element.createElement("tag_name");
This creates a new element with tag name: tag_name, and returns the id of this as
return value.
Example 3
6.4 Exercises
1. Which function on the document object should be used to retrieve a HTML element
uniquely?
31
DAA & Web Design Lab
2. Which JavaScript function can be used to dynamically add a event listener to a
HTML Element?
4. Using the DOM API, create a product details page which shows the prices of a
laptop and a cell phone. You may paragraph tag to wrap these elements. When the
user clicks on add button, you should able to add TV with price details and when you
click on delete button then cell phone details will be deleted.
7.0 Introduction
When executing a code or script, errors may occur. These errors can be mistakes made
in coding by the programmer, errors caused by providing wrong input, and due to
unforeseeable things.
7.1 Objectives
syntax:
try
{
set of statements to be executed.
}
catch: set of statements written to handle the error occurred in try segment.
Syntax:
32
catch Web
Web Design
DesignLab
Lab
{
set of statements to be executed when error occurs in try segment to handle
this error.
}
throw: set of statements used to create custom errors.
Syntax:
throw "Empty field"; // throw a text
throw 100; // throw a number
finally: set of statements executed, after try and catch segments, irrespective of their
result.
Syntax:
finally
{
set of statements executed, after try and catch segments, irrespective of their
result.
}
Example 1
In following HTML code error handling is used to address any error in the code.
<html>
<head>
<title>Error Handling in javascript</title>
</head>
<body>
Explanation:
as the function eval(), evaluates the expression passed as argument. In the code in try
, a ( 2= ) a a , d 2= a d
evaluate which is handled by the catch segment.
A built-in error object is defined in JavaScript which provides error information about
the error occurred.
The error object has two properties: name and message.
Name property: can set or return name of the error occurred.
Message property: can set or return an error message in the form of a string.
The error name property can define following values:
7.3 Exercises
1. Write an HTML code using JavaScriptto add two numbers taken as input from user
and display the result of division operation on them i.e. a/b. If an error occurs, show
the error. Use error handling concepts in JavaScript.
34
2. A teacher has created a gradeLabs function that verifies if student programming Web
Web Design
DesignLab
Lab
labs work. This function loops over an array of JavaScript objects that should contain
a student property and runLab property. The runLab property is expected to be a
function containing the student's code. The runLab function is called and the result is
compared to the expected result. If the result and expected result don't match, then the
lab is considered a failure.
3. There is an array of animals. The user is asked to enter the index for the animal they
want to see.
i) If the user enters an index that does NOT contain an animal, the code will throw a
TypeError when name is referenced on an undefined value.
ii) Update the above program to print out the index the user entered. We want this
message to be printed EVERY time the code runs
8.0 Introduction
In this session, we are going to explore JavaScript Classes. These classes were
introduced in ES6. These classes are used to support object-oriented paradigm in
JavaScript.
8.1 Objectives
JavaScript Classes are templates for creating Objects.JavaScript classes have two
components class expressions and class declarations.Similar to the function
expressions, class expressions can also be defined in two ways: named and
unnamed.The basic difference between class expression and class declaration method
of defining class is that when a class is defined as class expression, it runs as soon as it
is defined in contrast to class declaration. That is, use class declarations when the class
is to be made available throughout the code with global scope and class expressions is
used when we want to limit the scope of the class to where it is available.
Class expression syntax:
<script>
// unnamed method
35
DAA & Web Design Lab let Bike = class
{
//let is variable type in JavaScript
constructor(make)
{
this.make = make;
}
var bmodel()
{
d c . ( T d c );
}
};
document.write(Bike.name);
// output: "Bike"
</script>
Here, the class name is the variable name Bike.
<script>
// named method
let Bike = class Bike2
{
//let is variable type in JavaScript
constructor(make)
{
this.make = make;
}
};
document.write(Bike.name);
// output: "Bike2"
</script>
Here, ca a ca b d Bik 2. a ad Bik . a
because the scope of class name Bike2 d ca b d .
36
T c ab c a aca Bike" with initial property model. Web
Web Design
DesignLab
Lab
When an object of a class is created, the constructor method of its class is called
automatically. When a constructor method is not defined by the programmer,
JavaScript will add a default empty constructor by its own. After the constructor
method, class methods are created within the class. Class methods and class properties
can be access as follows:
class_object.class_method(Arguments list);
class_object.class_property;
Example 1: Create a Class with name Bike having two properties: B_make and
B_year and a method with name "age", that returns how many years old the bikeis.
Solution:
<script>
class Bike {
constructor(B_make, B_year)
{
this.B_make = B_make;
this.B_year = B_year;
}
age()
{
vardt = new Date();
var x = dt.getFullYear() - this.B_year
return x;
}
}
object_name.class_method(Argument_list);
Classes in JavaScript have the functionality of getter and setter functions. Using
gettermethodwecan get some data from a class and using setter method some fields of
c a ca b a dd d a .T d db
functions a a d d d.
Example 2:
37
DAA & Web Design Lab <html>
<head>
<title>Getter and Setter in JavaScript</title>
</head>
<body>
<script>
class Bike
{
constructor(make)
{
this.make = make;
}
get bname()
{
return this.make;
}
set bname(x)
{
this.make = x;
}
}
The important point here to note is that even though setter and getter defined with
a b a d b a d a () c
b a .A a a a d d b a
as the class property names.
In JavaScript, properties or methods of a parent class can be included in the child class
using inheritance. A child class can inherit all the properties and methods of a parent
class using the keyword d .
Inheritance extends the reusability of the code in JavaScript.
38
Solution: Web
Web Design
DesignLab
Lab
<html>
<body>
<script>
class Bike
{
constructor(make)
{
this.make = make;
}
present()
{
return 'My Bike is of type ' + this.make;
}
}
Explanation:
The function super() used in the constructor of the child class: BikeTyperefers to the
parent class: Bike.
Parent class constructor can be called when the super() method is called in the
constructor method of the derived or the child class. By doing so, the parent's
properties and methods can be accessed from the child class.
8.3 Exercises
39
DAA & Web Design Lab 1. Let us assume you need to organize a library of some electronic manuals and novels
for a particular company. For each book, you need to store following information:
The title
The author
The copyright date
The ISBN
The number of pages
The number of times the book has been checked out.
Whether the book has been discarded
Company wants to perform certain actions when the any book is outdated. The
manual books must be exited after 5 years while a novel book should be exited if its
checked out time crossed 100.
Task 1.Construct three classes that hold the information needed by company. One
class should be a Book class and two child classes of the Book class called Manual
and Novel. Each class will contain two methods. One will be a constructor. The other
one will either be in charge of disposal of the book or updating the property related to
the number of times a book has been checked out.
Task 2: Create an object of the Novel class and Manual class with some valid details.
Task 3: Write the method to count the duration of a manual book and checkout time
for novel book so that they can be discarded based on the duration.
2. C a a b c d c : ID, Na , D c a dP c .T
create function for this object called displayProductDetails(). This function when
invoked should display the name, description and discounted price of the product. For
the calculation of discounted price you need to create another function
CalculateDisc(percentage). The discount percentage would be given by user.
9.0 Introduction
Welcome to the session 8. In this session, we are going to learn the Asynchronous
programming in JavaScript and explore the Async keyword.
9.1 Objectives
In JavaScript the functions are not executed in the sequence they are defined, rather
executed in the sequence they are defined.
40
Sometimes functions are dependent on each other and are to be executed in a certain Web
Web Design
DesignLab
Lab
sequence. A function may need output of another function as input Therefore it cannot
be executed until the output of another function is available. This dependency cannot
be implemented by simply defining the order of function calling.
JavaScript implements Callbacks to provide more control on the sequence of function
execution. A Callback is a function which is passed as an argument to another
function. When a function is passed as an argument to a function, parenthesis are not
used for the function passed as an argument.
Example 1:
<html>
<head>
<title>JavaScript Callbacks</title>
</head>
<body>
<p>After performing addition, display the sum.</p>
<script>
function show(data)
{
document.write(data);
}
function add(x, y, abc)
{
var sum = x + y;
abc(sum);
}
add(3, 7, show);
</script>
</body>
</html>
Result:
Explanation:
The function show() is callbacks through the function add() by passing as an
argument. First, add() function is called and executed, then within add() function abc()
is linked with the show() function which is called by add() once the result of addition
is available.
Asynchronous functions are implemented with Callbacks in JavaScript. In
JavaScript the method setTimeout() is a typical example of asynchronous function.
41
DAA & Web Design Lab With setTimeout(myCallback, timeout_interval), the name of the callback function
can be passed as an argument which will be executed after the expiry of
timeout_interval.
Example 2:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Callbacks with SetTimeout()</title>
</head>
<body>
<p>Please wait for 5 sec (5000 milisecond).</p>
<script>
setTimeout(abc, 5000);
function abc()
{
document.write("This function executed on timeout");
}
</script>
</body>
</html>
Result:
After 5 seconds:
9.3 Exercises
1. Implement a clock in HTML which shows the live time in the format HH:MM:SS.
Use the JavaScript setInterval() method and a callback function by displaying the
system time every second.
2. Sometimes we use external resource files in our HTML page. The content of an
external file cannot be used until loaded completely. This can be implemented with
JavaScript Callback. Design a web page which loads an external HTML file on the
42
event: onLoad. Hint: use the inbuilt class XMLHttpRequest() to use its functions: Web
Web Design
DesignLab
Lab
open(), onLoad() etc. to load an external HTML file.
3.The village crows own an old scalpel that they occasionally use on special
missions say, to cut through screen doors or packaging. To be able to quickly track
it down, every time the scalpel is moved to another nest, an entry is added to the
storage of both the nest that had it and the nest that took it, under the name "scalpel",
with its new location as the value.This means that finding the scalpel is a matter of
following the breadcrumb trail of storage entries, until you find a nest where that
points at the nest itself.
Write an async function locateScalpel that does this, starting at the nest on which it
runs. You can use the anyStorage function defined earlier to access storage in
arbitrary nests. The scalpel has been going around long enough that you may assume
that every nest has a "scalpel" entry in its data storage.
Cookies are small piece of user data, stored as small text files, on the user/client-side
c . C a d a c
when user visits the website next time.
When a user submits a request to access a web page asURL to the browser, the
browser on behalf of user sends a request forthedesired web page to concerned server.
Here, before sending this request, browser checks for the cookies belonging to the
web page, if found are also added to the request. From this request with cookies the
server gets the required data to "remember" information about users.
10.1 Objectives
In this session, we are going to learn about cookies and sessions. The main objectives
of this session are as follows:
Learn to handle cookies
Delete, Send, and Receive cookies
Learn session tracking
43
DAA & Web Design Lab Here, this cookie stores user name in username, expires is the time after which this
cookie will be deleted automatically. In a cookie it is optional to mention the expiry
date and time. When expiry date and time is not mentioned in a cookie it will be
deleted when the browser is closed.
The path parameter tells the browser what path the cookie belongs to. If path
parameter is not set, by default it belongs to the current page.
The domain parameter is set to the root domain.
An existing cookie can be modified using the same statement as it was created. The
cookie parameters will be overwritten with the newly defined values.
Reading a Cookie in JavaScript
A cookie can be read by the following statement:
var c = document.cookie;
This statement will return cookies in the form of a single string as follows:
cookie1=value; cookie2=value; cookie3=value;
Deletion of a cookie in JavaScript is very easy. To delete a cookie all we need is to set
its expiry parameter to a past date. The following cookie will be deleted:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
We must specify the path parameter to ensure the deletion of right cookie.
The string returned by document.cookie is not a normal string instead it is the name-
value pair. A new cookie set does not overwrite the older cookies i.e. after setting the
new cookie on reading document.cookie again the following result will be displayed:
cookie1 = value; cookie2 = value;
Important here to note is that: when we want to access value of a particular cookie, a
JavaScript method is to be written which searches for the desired cookie value in the
cookie string.
Explanation:
The function set_Cookie() creates a cookie with name of the cookie ascookie_name,
value as cookie_value, and the age in days after, for which this cookie will alive.
Once we have set the cookie, now we will write a function that returns the value of the
cookie
function get_Cookie(cookie_name)
{
var c_name = cookie_name + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var c1 = decodedCookie.split(';');
for(var i = 0; i< c1.length; i++)
{
var c2 = c1[i];
while (c2.charAt(0) == ' ')
{
c2 = c2.substring(1);
}
if (c2.indexOf(c_name) == 0)
{
return c2.substring(c_name.length, c2.length);
}
}
return "";
}
As of now the cookie is created/set and a function is available to get the cookie. Now
whenever a visitor visits a web page the server always checks whether the cookie is
available or not.
Here is the function to check whether a cookie is set:
If the cookie is not found, it will set the cookie by prompting user provide name, and
set a cookies by calling the set_cookie() function to store the username cookie for 365
days:
function check_Cookie()
{
var usr=get_Cookie("username");
if (usr != "")
{
alert("Welcome again " + usr);
} else
{
usr = prompt("Please enter your name:","");
if (usr != null &&usr != "")
{
set_Cookie("username", usr, 30);
45
DAA & Web Design Lab }
}
}
Putting all these three function together to run and see how cookies works:
<!DOCTYPE html>
<html>
<head>
<script>
function set_Cookie(cookie_name,cookie_value,exp_days)
{
var dt = new Date();
dt.setTime(dt.getTime() + (exp_days*24*60*60*1000));
var age = "expires=" + dt.toGMTString();
document.cookie = cookie_name + "=" + cookie_value + ";" + age + ";path=/";
}
function get_Cookie(cookie_name)
{
var c_name = cookie_name + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var c1 = decodedCookie.split(';');
for(var i = 0; i< c1.length; i++)
{
var c2 = c1[i];
while (c2.charAt(0) == ' ')
{
c2 = c2.substring(1);
}
if (c2.indexOf(c_name) == 0)
{
return c2.substring(c_name.length, c2.length);
}
}
return "";
}
function check_Cookie()
{
var usr=get_Cookie("username");
if (usr != "")
{
alert("Welcome again " + usr);
} else
{
usr = prompt("Please enter your name:","");
if (usr != null &&usr != "")
{
set_Cookie("username", usr, 30);
}
}
46
} Web
Web Design
DesignLab
Lab
</script>
</head>
<body onload="check_Cookie()"></body>
</html>
Result:
For the first time, a prompt box is shown asking to enter the name.
Once the name is provided, afterwards, whenever we reload the page, it shows a
welcome message with the name entered.
10.3 Exercises
1.Create an HTML web page, as shown below. The cookie will be set on pressing
setCookie button and the stored cookie value will be displayed on pressing getCookie
button.
2.Considering exercise 1, modify the web page to display the cookie's name-value pair
separately as shown in figure below.
47
DAA & Web Design Lab
3. A list of color is provided in the form of drop down list. The background color of
the web page changes as per the selection of the color from the list by the user. At the
same time the chosencoloris passed to the cookie. The cookie stores the last choice of
a user in a browser which will be used on reloading the web page to display the same
color as background color.
4. Create an HTML web page, as shown below. The cookie1 and cookie2 will be set
on pressing Set Cookie1or Set Cookie2 button and the stored cookie value will be
displayed on pressing Get Cookie1 or Get Cookie2 button respectively. On the other
hand selectively cookie can be deleted by pressing Delete Cookie1 or Delete Cookie2
button. Display all cookies button will show all the stored cookies.
48
Web
Web Design
DesignLab
Lab
49
DAA & Web Design Lab
50