0% found this document useful (0 votes)
9 views36 pages

Js Example Codes1 - Level3

This document outlines a comprehensive course on HTML, CSS, and JavaScript, covering topics such as HTML forms, CSS styling, and JavaScript programming concepts including DOM manipulation, error handling, and asynchronous programming. The course is structured into multiple sessions, each with specific objectives aimed at providing hands-on experience and understanding of web development fundamentals. By the end of the course, students will be equipped with the skills to create and manage dynamic web pages effectively.

Uploaded by

narenn4406
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views36 pages

Js Example Codes1 - Level3

This document outlines a comprehensive course on HTML, CSS, and JavaScript, covering topics such as HTML forms, CSS styling, and JavaScript programming concepts including DOM manipulation, error handling, and asynchronous programming. The course is structured into multiple sessions, each with specific objectives aimed at providing hands-on experience and understanding of web development fundamentals. By the end of the course, students will be equipped with the skills to create and manage dynamic web pages effectively.

Uploaded by

narenn4406
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

HTML,JAVA SCRIPT AND CSS

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

JavaScript is a popular web programming language. It is generally used to validate the forms. JavaScript is based on
an object-oriented paradigm. In this lab, you will learn the advanced JavaScript concepts with hands-on practices.
Objectives

After completion of this course, student will be able to learn


● Basics of HTML forms and CSS
● The HTML DOM functionality, events and navigations
● Error Handling in JavaScript
● asynchronous programming in JavaScript

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

The objectives of this session are:


● Understand the basic JavaScript constructs
● Understand conditional statements and control flow statements

1.2 Enabling JavaScript

JavaScript can be included in html in two ways: Internal and external file.

● Internal JavaScript to HTML file:

JavaScript can be added to head, body or both sections.

<script> x = 3;

</script>

● Reference external file:

<head>

<script type = "text/javascript" src = "[Link]" ></script>

</head>
OR

<head>
<script src="[Link]
</script>

</head>

1.3 Conditionals and Loops:

Javascript provides conditional statements i.e. if. . . else, nested ifelse 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
}Example 2
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:
The code block “do something” within while loop is executed until
the condition i<n, is true.

● for loop:

Syntax:

for (statement1; statement2; statement3)


{
// for loop code block to be executed if statement2 is true
}

Where,

Statement1 is executed only once, before the execution of the loop code block.

Statement2 is the condition statement. The loop code block is executed only when
this condition is true.
Statement3 gets executed each time after execution of the loop code
block.

Example 3

for (var i=0; i<n; i++)

// loop code block

Output:

Here,

1. 1st vari=0 statement is executed,

2. i<n is executed,

3. if in step 2 (i<n) statement is true, loop code block is executed.

4. after finishing loop code block, i++ is executed.

This completes 1st cycle.

5. Now, omitting statement1 (var i=0), statement2 (i<n) is executed.

6. If statement2 (in step 5) is true, loop code block is executed.

7. After finishing loop code block statement3 (i++) is executed.

This completes 2nd cycle.

Now, 2nd cycle is executed until the condition meets false value.

1.4 Functions in JavaScript

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 function_name(parameter1, parameter2, parameter3)

{
// function code block to be executed
}
Example 4

function foo(x,y){

//function code block to be executed return x*y;

2.0 Session 2: HTML Forms

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

The objectives of this session are as follows:


● Understand the HTML Form element.
● Use the form element in HTML
● Use HTML to acquire user input and process it.
● Create forms with basic elements like textboxes checkboxes, radio buttons and submit buttons.
● Create forms using HTML5 elements like E-mail address field and form validation.

2.2 HTML Forms Elements


In HTML, user input is collected using the HTML Form element. The data collected from user is sent to server for
processing. HTML Form: a document, capable of storing data on a web server, provided by the user at run time. It is
usually used to collect information like: user name, user password, contact details like: mobile number, e-mail id etc. Some
of the commonly used elements in an HTML form are: input box, text box, check box, radio buttons, submit buttons etc.
Basic Elements of HTML forms:

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:
The <input> Element:
It is used to acquire user inputs
Following is the syntax of <input> element:
<input type=””>:
Here, type defines the way to acquire the user input i.e. text, radio button, checkbox, submit button.
Let's discuss the commonly used attributes of input element: - 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><input type="radio" id="opt3" name="opt" value="Option3">
<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="Ford”>
<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="/[Link]">
<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:

Example:
<input type="email">

<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 ><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:
<input type="url" name = “url>

type = “date”
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 = “date” id="dob" name="dob">
To show the month and year only:
<input type = “month” id="expiry" name="expiry" required>
To show the time only:
<input type=”time” id="time" name="time">

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.

Session 3: Cascading Style Sheet (CSS)


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

After completing this session, one should be able to:


● Create CSS for a webpage
● Embed CSS inline and external into an HTML code.

3.2 What is CSS?


A style sheet is a collection of rules describing the format and style of the HTML elements/tags. CSS can be embedded
into HTML code as: internal CSS and external CSS.
Structure of CSS:

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>

<h2>It is heading under internal CSS</h2>


<p> It is paragraph under internal CSS.</p>
</body>
</html>

3.2.2 Inline CSS:

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>

<h2 style="text-align:right; color:red;"> It is heading under inline CSS </h2>


<p style="text-align:justify; color:green;"> It is paragraph under inline CSS.</p>

</body>
</html>

3.2.3 External CSS:

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>

<h2> It is heading under external CSS</h2>


<p> It is paragraph under external CSS.</p>
</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.
Session 4: JavaScript HTML DOM

4.0 Introduction

In this session, we will discuss the DOM(Document Object Model). DOM is a standard defined by W3C (World
Wide Web Consortium). W3C DOM is an interface, which allows programs and scripts to access, add, modify and even
remove the content, structure, and style of an html document. It is a language independent interface.
The W3C DOM is categorized into 3 parts as follows:
● Core DOM – it is the standard model for all document types
● XML DOM – it is the standard model for XML documents
● HTML DOM – it is the standard model for HTML documents
In this Section we will be discussing about the HTML DOM only.

4.1 Objectives:

After completing this session one should be able to:


● Add, modify or delete the existing content of HTML elements
● Modify a CSS style in the html page
react to existing HTML DOM events in the html page.

4.2 HTML DOM

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>

<p>My first paragraph.


<h1>My First Heading</h1>
</p>
<!This is comment>
</body>
</html>
Element:
<head>
Element: <title>
Text: "My Title"
Element:<html>Element:<body>Comment: "This is comment"
Element: <p>

Text: "My first paragraph"


Element: <h1> Text: "My First
Heading"
Figure 1: HTML DOM of the HTML page shown in code 1.

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 [Link] 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.

4.2.1 HTML DOM Methods and Properties

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 [Link] DOM
properties: These are the values or attributes Elements of HTML page that could be set or updated.

4.2.2 The DOM Programming Interface

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
[Link] update an HTML element, first we need to access it by finding that particular element in the whole document or
the web [Link] 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.
[Link](id)

Following are the properties used to change an HTML Elements:

Property Description
[Link] Update the content of element: element
= new content (between opening and closing tags) with
content: new content

[Link] = Update the attribute values of the


new attribute value element: element with the new attribute values

[Link] Update the style of the element: element


ty = new style with the new style

Following are the methods used to add or remove HTML Elements:

Method Description

[Link](“element_name”) Create a new element: element_name under


the element: document.
Ex: [Link]("p"); It
creates a new element <p> under the body part.

[Link](child_element) Remove the element: child_element whose


parent is element: document.

[Link](child_element) Add element: child_element under the


element: document.

[Link](new, old) Replace element: old, with element: new of


the parent element document.
Following are the methods used to add event handlers:

Method Description

[Link](id).onclic It adds an onclick event to the element with ID: id,whose


k = function(){code} code is written in function: function()

Example 1: Write a javascript to change the contents of the paragraph element. Solution:
<p> with id="para1".
<html>
<body>
<p id="para1">This is to be updated using innerHTML</p>
<script>
[Link]("para1").innerHTML = "We have replaced using innerHTML";
</script>
</body>
</html> Result:
We have replaced using innerHTML

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".
The contents of any HTML element (even <html> and <body>) can be accessed and updated using the innerHTML
property.

Example 2: Write an HTML code with JavaScript in which the contents of the paragraph element
Solution:
<p> with id="para1"changes on click event.
<!DOCTYPE html>
<html>
<body>
<p id="para1" onclick="Fun()">Click here to change this text.</p>
<script> function Fun()
{
[Link]("para1").innerHTML = "The text is changed";
}
</script>
</body>
</html>

Result: Initially below page is shown:

Click here to change this text.

The text is changed

On mouse click on the text, below page is shown:

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".

4.2.3 Updating style of an HTML Element

Following syntax is used to change the style of an HTML element using HTML DOM:
[Link](element_id).[Link] = 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>

<h2 id="heading1">Old heading in red color</h2>


<p> the heading color changed from red to green</p>
<script>
[Link]("heading1").[Link] = "green";
</script>

</body>
</html>

Result: As shown below the color of the content of h2 element is changed from red to green.
Session 5: JavaScript HTML DOM events and Event Listener
5.0Introduction

JavaScript is capable of executing a script on occurrence of an event in HTML document i.e. on mouse click event on
an HTML element like button. The JavaScript code is added to the event attribute of the HTML element. In this session, you
will learn the about adding or removing the event listeners and methods about event listener.

5.1 Objectives

After completing this session, one should be able to:


● Add, modify or delete the HTML DOM events
● Work with event listeners
● Perform actions based on events using JavaScript

5.2 DOM Events

Following are the list of events commonly used in HTML DOM:


● Mouse click on an element, like: button, anchor, image etc.
● On load of a web page.
● On load of an image.
● On mouse movement over an element.
● On change in input field value.
● On submission of HTML form.
● On key press from keyboard etc.

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()
{ [Link] = "This is changed text after click";
</script>
}
</body>
</html>
Result: Before click:

After click:

5.2.1 Adding an event listener of an element

Event Listeners are attached to elements and fired when certain event [Link]() 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
[Link](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
capturin
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 and then the outer element's
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 element's
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>
[Link]("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 click an alert message
“This is first click” is shown and in second click an alert message “This is second click” is
shown.
Solution:
<!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> [Link]("btn1").addEventListener("click", abc1);
[Link]("btn1").addEventListener("click", abc2);

function abc1()
{
alert ("This is first click");
}
function abc2()
{
alert ("This is second click");
}
</script>
</body>
</html>

In the function called on an event, parameters can be passed. Parameter passing is done with the help of an
“anonymous function”.
Syntax:
[Link]("click", function(){ my_Function(a, b); });

5.2.2 Remove an event listener of an element

The method: removeEventListener() is used to removes an event handler of an element attached with the
addEventListener() method.
Syntax:
[Link]("event", function);

Session 6: HTML DOM Navigations

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
After completing this session, one should be able to:
● Add the navigations between nodes
● Create and remove HTML DOM element

6.2.
Following node properties can be used to navigating between nodes in JavaScript code:
● parentNode
● childNodes[nodenumber]
● firstChild
● lastChild
● nextSibling
● previousSibling
A node can be accessed either by its ID or by its class or by navigation properties of node.
Considering the HTML code below, following are the ways nodes can be accessed using navigational properties
of node:
<!DOCTYPE html>
<html>
<head>
<title>1st child of title element.</title>
</head>
<body>
<h3 id=”heading1”> 1st child of body element (which is the last child or 2nd child of the root element </h3>
<p id=”para1”>Second or the last child node of body element.</p>
</body>
</html>

[Link] ID of the element:


var elemt = [Link]("heading1").innerHTML;
[Link] the parent – child relationship:
var elemt = [Link]("heading1").[Link];
Here, [Link]("heading1") returns the access id of heading1 element, and
[Link]("heading1").firstChild points to the 1st child which is the text content of heading1 element,
and [Link]("heading1").[Link] returns the value of firstChild element of heading 1
element which is “1st child of body element (which is the last child or 2nd child of the root element” in this case”.
nodeValue is the property of node to access the value of the node.

The first child can also be accessed as follows:


var myTitle = [Link]("demo").childNodes[0].nodeValue; Where, childNodes is an array
which stores the list of child nodes of an element.
Other than nodeValue, some of the commonly used node property is: nodeName. It specifies the name of the tag of an
HTML element or node, which is always retuned in uppercase.

6.3 Creating and removing HTML elements using HTML DOM

An HTML element is created 1st and then appended before or after to an existing element.
The following syntax is used to create a new HTML element:
var new_element = [Link]("tag_name"); This creates a new element with
tag name: tag_name, and returns the id of this as return value.

Example 3

var para1 = [Link]("p");


This will create a new element <p> with id = para1. At present this element is not associated with any element of the
HTML document.
Note that, <> symbols are not used while specifying the name of the new element to be created.
To add the text to this <p> element, following command can be used:
var text_node = [Link]("A new text node is created"); By this, we have created two new
nodes represented by variables: para1 and text_node.
First this text node is to be added to the <p> node, which can be done using following syntax:
[Link](text_node);
Finally, the <p> element has to be appended to an existing HTML document's
element. This can be done as follows:
Considering, there exists a <div> element with id =d1 to which this newly created <p> element is to be added.
[Link]("d1").appendChild(para1);
The appendChild() adds the new element as the last child of the parent.
The insertBefore() method can be used instead of appendChild() to add a child at a specific position among the children
of parent.
Syntax: [Link](new_element,existing_element_before_new_is_inserted);
Here, the new_element is inserted as the child of the element:element, at the position: before the element:
existing_element_before_new_is_inserted.

6.3.1 Removing an HTML element

To remove an existing HTML element, remove() method is used. Syntax:


[Link]()
The element: element will be dropped.

6.3.2 Removing a child element

To remove a child element of a parent removeChild() method is used. Syntax:


[Link](child);
The element: child of the parent node: parent will be dropped.

Session 7: JavaScript Error Handling

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

After completing this session, one should be able to:


● Understand error handling mechanism
● Implement the different error cases with nested try catch blocks

7.2 Java Script error handling methods


The main terms that are used in JavaScript to handle the errors are describe as follows: try: set of statements
required to be executed in which the errors may occurred and are required to be addressed.

syntax: try
{
set of statements to be executed.
}
catch: set of statements written to handle the error occurred in try segment. Syntax:

catch
{

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.
Syn
tax:
finally
{
set of statements executed, after try and catch segments, irrespective of their result.
}

Putting all
together: try
{
set of statements to be executed.
}
catch(err)
{
set of statements to be executed when error occurs
in try segment to handle this error.
}
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>

<h2>Error Handling in JavaScript</h2>


<p id="para1"></p>
<scrip
t> try
{
eval("2=x");
catch(err)
}
{
[Link]("para1").innerHTML = [Link];
}
</script>
</body>
</html> Result:

Explanation:
as the function eval(), evaluates the expression passed as argument. In the code in try segment, eval(“2=x”) shows a
syntax error, due to the expression 2=x passed to 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:

Error Name Description

EvalError It shows that there exists an error in the eval()


function
RangeError It shows that a number has assigned a value "out
of its range".

ReferenceError It shows that a variable is accessed that has not


been declared

SyntaxError It shows that a syntax error is found in the code

TypeError A type error has occurred. Ex. trying to convert


a number to uppercase

URIError It shows that illegal characters are used in a


URI (Uniform Resource Identifier) function

Session 8: JavaScript Classes

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

After completing this session, one should be able to:


● understand object-oriented architecture
● define the objects and implement the methods
● make use of getters and setters

8.2 Java script classes

JavaScript Classes are templates for creating [Link] classes have two components class expressions and
class [Link] to the function expressions, class expressions can also be defined in two ways: named and
[Link] 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>
let Bike = class
// unnamed method
{
//let is variable type in JavaScript constructor(make)
{
[Link] = make;
}
var bmodel()
{
[Link](“This is inside the function”);
}
};
[Link]([Link]);
// 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)
{
[Link] = make;
}
};
[Link]([Link]);
// output: "Bike2"
</script>
Here, the class name cannot be printed using “[Link]” instead of “[Link]”
because the scope of class name “Bike2”is limited within the class body.

Class declaration syntax:


<script> class Bike
{
constructor(make)
{
[Link] = make;
}
var bmodel()
{
[Link](“This is inside the function”);
}
};
[Link]([Link]);
// output: "Bike"
</script>
The script above creates a class “Bike" with initial property model.

A JavaScript class is not an object rather it's a template for objects.


Once we have created class it can be used by creating object of it as follows:
var object_name = new class_name(Arg1_value, Arg2_value);

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 = [Link]() -
this.B_year return x;
}
}

varobject_bike = new Bike("Honda", 2021);


[Link] ="My bike is " + object_bike.age() + " years old.";
</script>

Arguments can also be passed to the Class methods as follows:

object_name.class_method(Argument_list);

8.2.1 Getters and Setters Function

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 the
class can be assigned desired values. The “get” keyword is used before the getter functions
name and “set” keyword for setter methods.

<html>
Example 2:
<head>
<title>Getter and Setter in JavaScript</title>
</head>
<body>
<script> class Bike
{
constructor(make)
{
[Link] = make;
}
get bname()
{
return [Link];
}
set bname(x)
{
[Link] = x;
}
}

var obj_bike = new Bike('TVS'); obj_bike.bname = 'Honda';


[Link](obj_bike.bname);
</script>
</body>
</html> Result:
Honda Explanation:

As we have defined getter function as “get bname() and setter function as “set bname(x)”, the value of class
property make can be set directly.

The important point here to note is that even though setter and getter defined with name “bname” is method but we
have not used parentheses () of function with “bname”. Another point to note is that the name of getter and setter should
not be same as the class property names.

8.2.2 Class Inheritance

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 “extends”.
Inheritance extends the reusability of the code in JavaScript.

Example 3:Create a class: BikeType to define whether it is a racer bike or a normal bike, which inherits the
methods of the class [Link]:

<html>
<body>

<script> class Bike


{
constructor(make)
{
[Link] = make;
}
present()
{
return 'My Bike is of type ' + [Link];
}
}

class BikeType extends Bike


{
constructor(make, bike_type)
{
super(make);
[Link] = make;
this.bike_type = bike_type;
}
show()
{
return [Link]() + ', it is a ' + this.bike_type;
}
}

var object_bike = new BikeType("Hero", "Racer");


[Link](object_bike.show());
</script>
</body>
</ht
ml>
Result:
My Bike is of type Hero, it is a Racer

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.

Session 9: JavaScript Asynchronous programming


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
After completing this session, one should be able to:
● Gain familiarity with what asynchronous JavaScript is, how it differs from
synchronous JavaScript, Differentials asynchronous JavaScript and Synchronous JavaScript
● Learn different use cases

9.2 Asynchronous Function

In JavaScript the functions are not executed in the sequence they are defined, rather executed in the sequence they
are [Link] functions are dependent on each other and are to be executed in a certain 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)
{
[Link](data);
}
function add(x, y, abc)
{
var sum = x + y;
abc(sum);
}
add(3, 7, show);
</script>
</body>
</ht
ml>
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. 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()
{
[Link]("This function executed on timeout");
}
</script>
</body>
</html> Result:

After 5 seconds:

Session 10: JavaScript Cookies


10.0 Introduction

Cookies are small piece of user data, stored as small text files, on the user/client-side computer. Cookies are used to
store user information on user's computer to use it when user visits the website next time.

Cookies are stored in the form name-value pairs as:


user_name = Devis Smith

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

10.2 Cookies in JavaScript Creating and deleting Cookie in JavaScript

In JavaScript cookies can be created, read, modified, and deleted using [Link] property.
A cookie is set or created using the statement as follows:
[Link] = "username=Devis Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/; domain=[Link]";
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 = [Link];
This statement will return cookies in the form of a single string as follows:
cookie1=value; cookie2=value; cookie3=value;

Deleting a Cookie in JavaScript

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: [Link] = "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 Cookie String

The string returned by [Link] 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 [Link] 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.

Setting a JavaScript Cookie

Let us learn setting of a cookie with an example.


● A cookie will be set which stores the name of a visitor.
● When a visitor visits the web page for the first time, he/she will be prompted
to provide his/her name which will be stored in a cookie.
● This cookie will be used when the visitor visits the web page next time to
show a welcome message.

Example 1:Implementing the above problem statement:


To implement this, following three javascript functions are to be created to:
1. create and set a cookie value
2. get a cookie value
3. check a cookie value
Function to create and set a cookie
The function below creates a cookie and sets values to its parameters to store the
visitor's name:function set_Cookie(cookie_name,cookie_value,exp_days) { var dt = new Date();
[Link]([Link]() + (exp_days*24*60*60*1000)); var age = "expires=" +
[Link]();
[Link] = cookie_name + "=" + cookie_value + ";" + age + ";path=/";
}

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([Link]); var c1
= [Link](';');
for(var i = 0; i< [Link]; i++)
{
var c2 = c1[i];
while ([Link](0) == ' ')
{
c2 = [Link](1);
}
if ([Link](c_name) == 0)
{
return [Link](c_name.length, [Link]);
}
}
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);
}
}

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();
[Link]([Link]() + (exp_days*24*60*60*1000)); var age = "expires=" +
[Link]();
[Link] = cookie_name + "=" + cookie_value + ";" + age + ";path=/";
}
function get_Cookie(cookie_name)
{
var c_name = cookie_name + "=";
var decodedCookie = decodeURIComponent([Link]); var c1 =
[Link](';');
for(var i = 0; i< [Link]; i++)
{
var c2 = c1[i];
while ([Link](0) == ' ')
{
c2 = [Link](1);
}
if ([Link](c_name) == 0)
{
return [Link](c_name.length, [Link]);
}
}
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);
}
}}
</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.

You might also like