IP Lab - Final Lab Manual 2024-25
IP Lab - Final Lab Manual 2024-25
IP Lab - Final Lab Manual 2024-25
LAB MANUAL
Semester: V
ITL501 - IP Lab
MGM’s College of Engineering and Technology
Vision:
To become one of the outstanding Engineering Institute in India by providing a conductive and
vibrant environment to achieve excellence in the field of Technology.
Mission:
To empower the aspiring professional students to be prudent enough to explore the world of
technology and mould them to be proficient to reach the pinnacle of success in the competitive
global economy.
Vision:
To emerge out as a prominent department offering a programme in its pursuit for academic
excellence in order to develop professionally competent and socially responsible Information
Technologists capable of meeting industry demands and social obligations in a vibrant global
environment.
Mission:
To strive towards building an atmosphere that will be a catalyst for innovative ideas and learning.
Providing IT students with various opportunities and experiences that can help them to thrive and
prosper through a blend of academics, practical exposure and research programs. To pursue
successful careers in a global environment.
i
ITL501 - IP Lab
ii
ITL501 - IP Lab
Course Objective:
Course Outcomes(CO):
iii
ITL501 - IP Lab
Program Specific Outcomes (PSO)
PSO1 Analyze real life problems and design user friendly solutions.
PO2) Problem Analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO3) Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate consideration
for the public health and safety, and the cultural, societal, and environmental considerations.
PO4) Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5) Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
PO6) The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7) Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
PO8) Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
iv
ITL501 - IP Lab
PO9) Individual and teamwork: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
PO11) Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12) Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.
ITL501 - IP Lab
CO & PO Mapping:
Program Outcomes (PO) Map
Name of
the CO PO PO PO PO PO PO PO PO PO PO PO PO
course code 1 2 3 4 5 6 7 8 9 10 11 12
- - _ - - - - - -
1 Low
- - - - - - - -
2 Low
- - - - - - - Medium
IP 3
Lab - - - - - -
- -
4 Medium
- - - - - - - Medium
5
- - - - - -
6 Medium
1 _ - Low
2 - Medium
3 _ - Low
IP Lab
4 - Medium
5 - Medium
6 - Medium
vi
ITL501 - IP Lab
LIST OF EXPERIMENTS
Page
Sr. No Name of Experiment CO PO PSO
No.
Creating web pages for College Website
01 CO1 PO1 PSO1 1
using different HTML5 tags.
Creating a webpage with cascading style
02 CO2 PO1 PSO1 10
sheet
Creating a responsive web page using
03 CO3 PO1,PO2 PSO1 14
Bootstrap.
Program based on JavaScript Variables,
vii
ITL501 - IP Lab
Experiment No. 1
Creating a webpage using different HTML5 tags.
Aim: To create web pages for College Website with the following
5: HTML tags.
i) Elements, Attributes, Head, Body, Hyperlink, Formatting, Lists
ii) Images, Tables
iii) Frames, Forms
Objective: To understand and use different HTML5 tags for creating a web page.
Theory:
HTML Elements
An HTML file is made of elements. These elements are responsible for creating web pages
and define content in that webpage. An element in HTML usually consist of a start tag <tag name>,
close tag </tag name> and content inserted between them.
HTML Attribute
HTML attributes are special words which provide additional information about the elements.
Each element or tag can have attributes, which defines the behaviour of that element.
Attributes should always be applied with start tag.
The Attribute should always be applied with its name and value pair.
The Attributes name and values are case sensitive
Syntax
<element attribute_name="value">content</element>
Example
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> This is Style attribute</h1>
<p style="height: 50px; color: blue">It will add style property in element</p>
<p style="color: red">It will change the color of content</p>
</body>
</html>
HTML Heading
A HTML heading or HTML h tag can be defined as a title or a subtitle which you want to
display on the webpage. When you place the text within the heading tags <h1>.........</h1>, it is
displayed on the browser in the bold format and size of the text depends on the number of heading.
There are six different HTML headings which are defined with the <h1> to <h6> tags, from
highest level h1 (main heading) to the least level h6 (least important heading).
Example:
<!DOCTYPE html>
<html>
<head>
<title>Heading elements</title>
</head>
<body>
<h1>This is main heading of page. </h1>
<p>h1 is the most important heading, which is used to display the keyword of page </p>
<h2>This is first sub-heading</h2>
ITL501 - IP Lab 1
<p>h2 describes the first sub heading of page. </p>
<h3>This is Second sub-heading</h3>
<p>h3 describes the second sub heading of page.</p>
<p>We can use h1 to h6 tag to use the different sub-heading with their paragraphs if
required.
</p>
</body>
</html>
HTML Formatting
HTML Formatting is a process of formatting text for better look and feel. HTML provides us
ability to format text without using CSS. There are many formatting tags in HTML. These tags are
used to make text bold, italicized, or underlined. There are almost 14 options available that how text
appears in HTML and XHTML.
In HTML the formatting tags are divided into two categories:
Physical tag: These tags are used to provide the visual appearance to the text.
Logical tag: These tags are used to add some logical or semantic value to the text.
Element Description
name
<b> This is a physical tag, which is used to bold the text written between it.
<strong> This is a logical tag, which tells the browser that the text is important.
<i> This is a physical tag which is used to make text italic.
<em> This is a logical tag which is used to display content in italic.
<mark> This tag is used to highlight text.
<u> This tag is used to underline text written between it.
<tt> This tag is used to appear a text in teletype. (not supported in HTML5)
<strike> This tag is used to draw a strikethrough on a section of text. (Not supported in HTML5)
<sup> It displays the content slightly above the normal line.
<sub> It displays the content slightly below the normal line.
<del> This tag is used to display the deleted content.
<ins> This tag displays the content which is added
<big> This tag is used to increase the font size by one conventional unit.
<small> This tag is used to decrease the font size by one unit from base font size.
HTML Hyperlinks
The HTML anchor tag defines a hyperlink that links one page to another page. It can create hyperlink to
other web page as well as files, location, or any URL. The "href" attribute is the most important attribute of the
HTML a tag.href attribute of HTML anchor tag and which links to destination page or URL.
The href attribute is used to define the address of the file to be linked. In other words, it points out the
destination page.
The syntax of HTML anchor tag is given below. Example:
<a href = "..........."> Link Text </a> <!DOCTYPE html>
Appearance of HTML anchor tag <html>
An unvisited link is displayed underlined and <head>
blue. <title></title>
A visited link displayed underlined and purple. </head>
An active link is underlined and red. <body>
Specify a location for Link using target attribute <p>Click on <a href="https://www.javatpoint.com/" target="
ITL501 - IP Lab 2
If we want to open that link to another _blank">this-
page then we can use target attribute of <a> tag. link </a>to go on home page of JavaTpoint.</p>
With the help of this link will be open in next page. </body>
</html>
HTML Lists
HTML Lists are used to specify lists of information. All lists may contain one or more list elements. There are three
different types of HTML lists:
Ordered List or Numbered List (ol)
Unordered List or Bulleted List (ul)
Description List or Definition List (dl)
HTML Ordered List or HTML Unordered List HTML Description List or Definition List
Numbered List or Bulleted List HTML Description list is also a list style which is
In the ordered HTML In HTML Unordered supported by HTML and XHTML. It is also known as
lists, all the list items are list, all the list items are definition list where entries are listed like a dictionary or
marked with numbers by marked with bullets. It is encyclopedia.
default. It is known as also known as bulleted The definition list is very appropriate when you want to
numbered list also. The list also. The Unordered present glossary, list of terms or other name-value list.
ordered list starts with list starts with <ul> tag The HTML definition list contains following three tags:
<ol> tag and the list items and list items start with <dl> tag defines the start of the list.
start with <li> tag. the <li> tag. <dt> tag defines a term.
ul> <dd> tag defines the term definition (description).
<ol> <li>Aries</li>
<li>Aries</li> <li>Bingo</li> <dl>
<li>Bingo</li> <li>Leo</li> <dt>Aries</dt>
<li>Leo</li> <li>Oracle</li> <dd>-One of the 12 horoscope sign.</dd>
<li>Oracle</li> </ul> <dt>Bingo</dt>
</ol> Output: <dd>-One of my evening snacks</dd>
Output: Aries <dt>Leo</dt>
1. Aries Bingo <dd>It is also an one of the 12 horoscope sign.</dd>
2. Bingo Leo <dt>Oracle</dt>
3. Leo Oracle <dd>It is a multinational technology corporation.</dd>
4. Oracle </dl>
Aries
-One of the 12 horoscope sign.
Bingo
-One of my evening snacks
Leo
-It is also an one of the 12 horoscope sign.
Oracle
-It is a multinational technology corporation.
HTML Image
HTML img tag is used to display image on the web page. HTML img tag is an empty tag that contains
attributes only, closing tags are not used in HTML image element.
Let's see an example of HTML image.
<h2>HTML Image Example</h2>
<img src="good_morning.jpg" alt="Good Morning Friends"/>
Attributes of HTML img tag
The src and alt are important attributes of HTML img tag. All attributes of HTML image tag are given
below.
1) src: It is a necessary attribute that describes the source or path of the image. It instructs the browser where
to look for the image on the server.The location of image may be on the same directory or another server.
2) alt : The alt attribute defines an alternate text for the image, if it can't be displayed. The value of the alt
attribute describe the image in words. The alt attribute is considered good for SEO prospective.
3) width: It is an optional attribute which is used to specify the width to display the image. It is not
recommended now. You should apply CSS in place of width attribute.
ITL501 - IP Lab 3
4) height: It h3 the height of the image. The HTML height attribute also supports iframe, image and object
elements.
Use of height and width attribute with img tag
You have learnt about how to insert an image in your web page, now if we want to give some
height and width to display image according to our requirement, then we can set it with height and
width attributes of image.
Example:
<img src="animal.jpg" height="180" width="300" alt="animal image">
HTML Table
HTML table tag is used to display data in tabular form (row * column). There can be many
columns in a row. We can create a table to display data in tabular form, using <table> element, with
the help of <tr> , <td>, and <th> elements.
HTML Table Tags HTML Table Example
Let's see the example of HTML table tag. It
Tag Description output is shown above.
<table>
<table> It defines a table. <tr><th>First_Name</th><th>Last_Name</t
<tr> It defines a row in a table. h><th>Marks</th></tr>
<tr><td>Sonoo</td><td>Jaiswal</td><td>60
<th> It defines a header cell in a table. </td></tr>
<tr><td>James</td><td>William</td><td>80
<td> It defines a cell in a table. </td></tr>
<tr><td>Swati</td><td>Sironi</td><td>82</
<caption> It defines the table caption.
td></tr>
<colgroup> It specifies a group of one or more columns in a <tr><td>Chetna</td><td>Singh</td><td>72<
table for formatting. /td></tr>
</table>
<col> It is used with <colgroup> element to specify
column properties for each column.
<tbody> It is used to group the body content in a table.
<thead> It is used to group the header content in a table.
<tfooter> It is used to group the footer content in a table.
HTML iframes
HTML Iframe is used to display a nested webpage (a webpage within a webpage). The HTML <iframe>
tag defines an inline frame, hence it is also called as an Inline frame.
An HTML iframe embeds another document within the current HTML document in the rectangular
region.
The webpage content and iframe contents can interact with each other using JavaScript.
Iframe Syntax: An HTML iframe is defined with the <iframe> tag:
<iframe src="URL"></iframe>
Here, "src" attribute specifies the web address (URL) of the inline frame page.
Set Width and Height of iframe
You can set the width and height of iframe by using "width" and "height" attributes. By default, the
attributes values are specified in pixels but you can also set them in percent. i.e. 50%, 60% etc.
Example: (Pixels)
<!DOCTYPE html>
<html>
<body>
<h2>HTML Iframes example</h2>
ITL501 - IP Lab 4
<p>Use the height and width attributes to specify the size of the iframe:</p>
<iframe src="https://www.javatpoint.com/" height="300" width="400"></iframe>
</body>
</html>
Example: (Percentage)
<!DOCTYPE html>
<html>
<body>
<h2>HTML Iframes</h2>
<p>You can use the height and width attributes to specify the size of the iframe:</p>
<iframe src="https://www.javatpoint.com/" height="50%" width="70%"></iframe>
</body>
</html>
Iframe Target for a link
You can set a target frame for a link by using iframe. Your specified target attribute of the link must refer to the
name attribute of the iframe.
Example:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Embed YouTube video using iframe
You can also add a YouTube video on your webpage using the <iframe> tag. The attached
video will be played at your webpage and you can also set height, width, autoplay, and many more
properties for the video.
Following are some steps to add YouTube video on your webpage:
Goto YouTube video which you want to embed.
Click on SHARE ➦ under the video.
Click on Embed <> option.
Copy HTML code.
Paste the code in your HTML file
Change height, width, and other properties (as per requirement).
Example:
<iframe width="550" height="315" src="https://www.youtube.com/embed/JHq3pL4cdy4" frameborder="0" allow=
"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-
picture" allowfullscreen style="padding:20px;"></iframe>
<iframe width="550" height="315" src="https://www.youtube.com/embed/O5hShUO6wxs" frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-
picture" style="padding:20px;">></iframe>
Attributes of <iframe>
Attribute Value Description
name
ITL501 - IP Lab 5
HTML5).
Width Pixels It defines the width of embedded frame, and default width is 300 px.
src URL The src attribute is used to give the path name or file name which content to be
loaded into iframe.
This attribute is used to apply extra restrictions for the content of the frame
allow-forms It allows submission of the form if this keyword is not used then form
submission is blocked.
sandbox allow-popups It will enable popups, and if not applied then no popup will open.
allow-scripts It will enable the script to run.
allow-same- If this keyword is used then the embedded resource will be treated as
origin downloaded from the same source.
srcdoc The srcdoc attribute is used to show the HTML content in the inline iframe. It
overrides the src attribute (if a browser supports).
It indicates that browser should provide a scroll bar for the iframe or not. (Not
supported in HTML5)
scrolling auto Scrollbar only shows if the content of iframe is larger than its dimensions.
yes Always shows scroll bar for the iframe.
no Never shows scrollbar for the iframe.
HTML Form
An HTML form is a section of a document which contains controls such as text fields,
password fields, checkboxes, radio buttons, submit button, menus etc.
An HTML form facilitates the user to enter data that is to be sent to the server for processing
such as name, email address, password, phone number, etc. .
HTML Form Syntax
<form action="server url" method="get|post">
//input controls e.g. textfield, textarea, radiobutton, button
</form>
ITL501 - IP Lab 6
<button> It defines a clickable button.
HTML 5 Form Tags
Let's see the list of HTML 5 form tags.
Tag Description
ITL501 - IP Lab 7
<input type="checkbox" id="cricket" name=" <input type="text" id="name" name="name"><br>
cricket" value="cricket"/> <label for="pass">Enter Password</label><br>
<label for="cricket">Cricket</label> <br> <input type="Password" id="pass" name="pass"><br>
<input type="checkbox" id="football" name= <input type="submit" value="submit">
"football" value="football"/> </form>
<label for="football">Football</label> <br HTML <fieldset> element:
> The <fieldset> element in HTML is used to group the
<input type="checkbox" id="hockey" name= related information of a form. This element is used with
"hockey" value="hockey"/> <legend> element which provide caption for the grouped
<label for="hockey">Hockey</label> elements.
</form> Example:
Submit button control <form>
HTML <input type="submit"> are used to add a <fieldset>
submit button on web page. When user clicks on <legend>User Information:</legend>
submit button, then form get submit to the server. <label for="name">Enter name</label><br>
Syntax: <input type="text" id="name" name="name"><br>
<input type="submit" value="submit"> <label for="pass">Enter Password</label><br>
The type = submit , specifying that it is a submit <input type="Password" id="pass" name="pass"><br>
button <input type="submit" value="submit">
The value attribute can be anything which we write on </fieldset>
button on web page. lt;/form>
The name attribute can be omit here.
Results:
Conclusion:
References:
1. HTML 5 Black Book (Covers CSS3, JavaScript, XML, XHTML, AJAX, PHP, jQuery) 2Ed., DT Editorial
Services
2. https://tutorialspoint.com/
Industrial Application:
To build responsive web application.
ITL501 - IP Lab 8
Questionnaire:
1. The purpose of markup is to
a) add hypertext capabilitiesb) enhance the document
c) both A & Bd) none of the mentioned
4. Which one of the following tags is used to insert graphics in the webpage
a) <image>b) <images>c) <img>d) <graphics>
5. The following html tag is used to display the content as a moving text
a) <marquee>b) </img>c) <a href>d) none of the mentioned
9. What is HTML?
a) HTML describes the structure of a webpage
b) HTML is the standard markup language mainly used to create web pages
c) HTML consists of a set of elements that helps the browser how to view the content
d) All of the mentioned
ITL501 - IP Lab 9
Experiment No.2
Creating a webpage with cascading style sheet
Aim:Creating a webpage with cascading style sheet
Objective: To create a web page that displays college information using various style sheet
Theory:
Cascading Style Sheet(CSS) is used to set the style in web pages that contain HTML elements. It
sets the background color, font-size, font-family, color, … etc property of elements on a web
page.
There are three types of CSS which are given below:
Inline CSS
Internal or Embedded CSS
External CSS
Inline CSS: Inline CSS contains the CSS property in the body section attached with element is
known as inline CSS. This kind of style is specified within an HTML tag using the style attribute.
<!DOCTYPE html>
<html>
<head>
<title>Inline CSS</title>
</head>
<body>
<pstyle = "color:#009900; font-size:50px;
font-style:italic; text-align:center;">
M GM CET!!!
</p>
</body>
</html>
Internal or Embedded CSS: This can be used when a single HTML document must be styled
uniquely. The CSS rule set should be within the HTML file in the head section i.e the CSS is
embedded within the HTML file.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Internal CSS</title>
<style>
.main {
text-align:center;
}
.mgm {
ITL501 - IP Lab 10
color:#009900;
font-size:50px;
font-weight:bold;
}
.cet {
font-style:bold;
font-size:20px;
}
</style>
</head>
<body>
<divclass= "main">
<divclass="mgm">M GM CET........</
div>
<divclass="cet" >
Welcome to M GM CET!!!
</div>
</div>
</body>
</html>
External CSS: External CSS contains separate CSS file which contains only style property with the
help of tag attributes (For example class, id, heading, … etc). CSS property written in a separate file
with .css extension and should be linked to the HTML document using link tag. This means that for
each element, style can be set only once and that will be applied across web pages.
Example: The file given below contains CSS property. This file save with .css extension. For
Ex: mgm.css
body {
background-color:powderblue;
}
.main {
text-align:center;
}
.mgm {
color:#009900;
font-size:50px;
font-weight:bold;
}
#cet {
font-style:bold;
font-size:20px;
}
Below is the HTML file that is making use of the created external style sheet
ITL501 - IP Lab 11
link tag is used to link the external style sheet with the html webpage.
href attribute is used to specify the location of the external style sheet file.
<!DOCTYPE html>
<html>
<head>
<linkrel="stylesheet"href="mgm.css" />
</head>
<body>
<divclass= "main">
<divclass="mgm">M GM CET.......</ div>
<divid="cet" >
Welcome to M GM CET!!!
</div>
</div>
</body>
</html>
Results:
Conclusion:
References:
1. HTML 5 Black Book (Covers CSS3, JavaScript, XML, XHTML, AJAX, PHP, jQuery) 2Ed., DT Editorial
Services
2. https://tutorialspoint.com/
Industrial Application:
To build responsive web application.
ITL501 - IP Lab 12
Questionnaire:
1. Which of the following tag is used to embed css in html page?
a) <css>b) <!DOCTYPE html>c) <script>d) <style>
2. Which of the following CSS selectors are used to specify a group of elements?
a) tagb) idc) classd) both class and tag
2. Which of the following has introduced text, list, box, margin, border, color, and background properties?
a) HTMLb) PHPc) CSSd) Ajax
3. Which of the following type of HTML tag is used to define an internal style sheet?
a) <script>b) <link>c) <class>d) <style>
4. Which of the following CSS property is used to make the text bold?
a) text-decoration: boldb) font-weight: boldc) font-style: boldd) text-align: bold
5. Which of the following CSS style property is used to specify an italic text?
a) styleb) fontc) font-styled) @font-face
Which of the following is the correct syntax to link an external style sheet in the HTML file?
a) <link rel=”stylesheet” href=”style.css” />b) <link rel=”stylesheet” src=”style.css” />
c) <style rel=”stylesheet” src=”style.css” />d) <style rel=”stylesheet” link=”style.css” />
6. Which of the following CSS property can be used to set the image as a border instead of the border style?
a) background-image-sourceb) background-imagec) border-image-sourced) border-image
9. Which of the following CSS property defines the different properties of all four sides of an element’s border
in a single declaration?
a) border-collapseb) border-widthc) paddingd) border
10. Which of the following CSS property sets what kind of line decorations are added to an element, such as
underlines, overlines, etc?
a) text-decorationb) text-stylec) text-decoration-lined) text-line
ITL501 - IP Lab 13
Experiment No.3
Bootstrap
Aim:Creating a webpage using Bootstrap Grid system, Forms, Button, Navbar, Breadcrumb,
and Jumbotron
Objective: To understand the concept of bootstrap and create responsive webpage by adding grid
system, form elements, buttons, etc.
Theory:
What is Bootstrap
Bootstrap is the most popular HTML, CSS and JavaScript framework for developing a responsive
and mobile friendly website.
It is absolutely free to download and use.
It is a front-end framework used for easier and faster web development.
It includes HTML and CSS based design templates for typography, forms, buttons, tables,
navigation, modals, image carousels and many others.
It can also use JavaScript plug-ins.
It facilitates you to create responsive designs.
History of Bootstrap
Bootstrap was developed by Mark Otto and Jacob Thornton at Twitter. It was released as an
open source product in August 2011 on GitHub. In June 2014 Bootstrap was the No.1 project on
GitHub.
Why use Bootstrap
Following are the main advantage of Bootstrap:
It is very easy to use. Anybody having basic knowledge of HTML and CSS can use
Bootstrap.
It facilitates users to develop a responsive website.
It is compatible on most of browsers like Chrome, Firefox, Internet Explorer, Safari and
Opera etc.
What is a responsive website
A website is called responsive website which can automatically adjust itself to look good on
all devices, from smart phones to desktops etc.
First Bootstrap Example
Add the HTML 5 doctype: Bootstrap uses HTML elements and CSS properties, so you have
to add the HTML 5 doctype at the beginning of the page with lang attribute and correct character set.
<!DOCTYPE html>
<html lang="en">
<head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Any title</title>
</head>
<body>
//write code
</body>
</html>
ITL501 - IP Lab 14
The initial-scale=1 part is used to set the initial zoom level when the page is first loaded by the
browser.
Containers: container is used to wrap the site contents. There are two container classes.
The .container class provides a responsive fixed width container.
The .container-fluid class provides a full width container, spanning the entire width of the
viewport.
Bootstrap Grid:
In graphic design, a grid is a structure (usually two-dimensional) made up of a series of
intersecting straight (vertical, horizontal) lines used to structure the content.
Bootstrap Grid System
The Bootstrap Grid System allows up to 12 columns across the page. You can use all 12
columns individually or you can groups the columns together to create wider columns.
Bootstrap Grid System is responsive and the columns are re-arranged automatically
according to the screen size.
Bootstrap 4 Grid Classes
There are 5 classes in Bootstrap 4 grid system.
.col- (extra small devices - screen width less than 576px)
.col-sm- (small devices - screen width equal to or greater than 576px)
.col-md- (medium devices - screen width equal to or greater than 768px)
.col-lg- (large devices - screen width equal to or greater than 992px)
.col-xl- (xlarge devices - screen width equal to or greater than 1200px)
Bootstrap Grid Example : For equal columns:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Job</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.c
ss"/>
</head>
<body>
<div class="container">
<h1>Grid Example</h1>
<div class="row">
<div class="col-md-3"style="background-color:lavender;">Rahul</div>
<div class="col-md-3"style="background-color:lavenderblush;">Vijay</div>
<div class="col-md-3"style="background-color:lavender;">Kartik</div>
<div class="col-md-3"style="background-color:lavenderblush;">Ajeet</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
ITL501 - IP Lab 15
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
Bootstrap Buttons
There are seven styles to add a button in Bootstrap. Use the following classes to achieve the different
button styles:
.btn-default
.btn-primary
.btn-success
.btn-info
.btn-warning
.btn-danger
.btn-link
Bootstrap Button Example: specifying seven styles
<!DOCTYPE html>
<html lang="en">
<head>
<title>Job</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.c
ss"/>
</head>
<body>
<h1>Button Example!</h1>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
Bootstrap Navigation Bar
A navigation bar is like a navigation header that is placed at the top of the page. You can collapse or
extend it according to the screen size.
You can create a standard navigation bar at the top of the page with with <nav class="navbar navbar-
default">.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Case</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css
">
ITL501 - IP Lab 16
</head>
<body>
<div class="container">
<h3>Basic Navbar Example</h3>
<p>A navigation bar is a navigation header that is placed at the top of the page.</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
Bootstrap Jumbotron
A Bootstrap jumbotron specifies a big box for getting extra attention to some special content
or information. It is displayed as a grey box with rounded corners. It can also enlarge the font sizes
of the text inside it.
You can put any valid HTML or other Bootstrap elements/ classes inside a jumbotron.
The class .jumbotron within the <div> element is used to create a jumbotron.
Jumbotron Inside Container
The Inside container is used in jumbotron, if you want the jumbotron to not extend to the
edge of the screen.Put the jumbotron inside the <div class="container">.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css
">
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>This is Jumbotron inside container!</h1>
<p>Jumbotron specifies a big box for getting extra attention to some special content or informatio
n.</p>
ITL501 - IP Lab 17
</div>
<p>This is some text.</p>
<p>This is another text.</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
Bootstrap Breadcrumb :
Indicate the current page’s location within a navigational hierarchy that automatically adds
separators via CSS.
Since breadcrumbs provide a navigation, it’s a good idea to add a meaningful label such
as aria-label="breadcrumb" to describe the type of navigation provided in the <nav> element, as well
as applying an aria-current="page" to the last item of the set to indicate that it represents the current
page.
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item active" aria-current="page">Home</li>
</ol></nav>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="#">Home</a></li>
<li class="breadcrumb-item active" aria-current="page">Library</li>
</ol></nav>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="#">Home</a></li>
<li class="breadcrumb-item"><a href="#">Library</a></li>
<li class="breadcrumb-item active" aria-current="page">Data</li>
</ol></nav>
Results:
Problem Statement: Create a webpage using Bootstrap Grid, Bootstrap Navbar and Bootstrap
Form.
Combine Bootstrap Grid, Breadcrumb and Form
MGM’s College of Engineering and Technology
Kamothe, Navi Mumbai – 410209
Home > About > Department > Contact Us > Feedback
Contact Us: Feedback :
College Address Full Name:
Email id:
Write Here :
Submit
ITL501 - IP Lab 18
Conclusion:
References:
1. HTML 5 Black Book (Covers CSS3, JavaScript, XML, XHTML, AJAX, PHP, jQuery) 2Ed., DT Editorial
Services
2. https://tutorialspoint.com/
Industrial Application:
To build responsive web application.
ITL501 - IP Lab 19
Questionnaire:
Q1. Which of the following CSS framework is used to create a responsive design?
a) django b) rails c) larawell d) bootstrap
Q3. Which of the following class in Bootstrap is used to provide a responsive fixed width container?
a) .container-fixed b) .container-fluid c) .container d) All of the above
Q5. Which of the following class in bootstrap is used to create a big box for calling extra attention?
a) .box b).container c) .container-fluid d).jumbotron
Q7. Which of the following is the correct syntax of creating a standard navigation tab?
a) <ul class="navigation nav-tabs"> b) <ul class="nav tab">
c) <ul class="nav nav-tabs"> d) <ul class="navigation tabs">
Q8. Which of the following class is used to create a black navigation bar?
a) .navbar-default b) .navbar-inverse c) .navbar-black d) .navbar-dark
ITL501 - IP Lab 20
Experiment No. 4
JavaScript Loops, Functions, Arrays and Strings
Aim: Program based on JavaScript Variables, Operators, Conditions, Loops, Functions, Arrays,
String and Date.
Theory:
JavaScript is an object-based scripting language which is lightweight and cross-platform.
JavaScript is not a compiled language, but it is a translated language. The JavaScript Translator
(embedded in the browser) is responsible for translating the JavaScript code for the web browser.
JavaScript Variable
JavaScript variable
JavaScript Local variable
JavaScript Global variable
A JavaScript variable is simply a name of storage location. There are two types of variables in
JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
After first letter we can use digits (0 to 9), for example value1.
JavaScript variables are case sensitive, for example x and X are different variables.
Example of JavaScript variable
<script>
var x = 10; var y = 20;
var z=x+y; document.write(z);
</script>
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. There are following
types of operators in JavaScript.
Arithmetic Operators Comparison (Relational) Operators
Bitwise Operators Logical Operators
Assignment Operators Special Operators
JavaScript Arithmetic Operators JavaScript Comparison Operators
Arithmetic operators are used to perform The JavaScript comparison operator compares the
arithmetic operations on the operands. two operands. The comparison operators are as follows:
++ Increment var a=10; a++; Now a = >= Greater than or equal to 20>=10 = true
11
< Less than 20<10 = false
-- Decrement var a=10; a--; Now a =
9 <= Less than or equal to 20<=10 = false
ITL501 - IP Lab 21
JavaScript Bitwise Operators JavaScript Logical Operators
The bitwise operators perform bitwise The following operators are known as
operations on operands. The bitwise operators are as JavaScript logical operators.
follows:
Operator Description Example
Operator Description Example
&& Logical AND (10==20 && 20==33) =
& Bitwise AND (10==20 & 20==33) = false
false
|| Logical OR (10==20 || 20==33) = false
| Bitwise OR (10==20 | 20==33) =
false
! Logical Not !(10==20) = true
^ Bitwise XOR (10==20 ^ 20==33) =
false
JavaScript Conditions
The JavaScript if-else statement is used to execute the code whether condition is true or false.
There are three forms of if statement in JavaScript.
If Statement
If else statement
if else if statement
JavaScript If statement JavaScript If...else if statement
It evaluates the content only if expression is It evaluates the content only if expression is
true. true from several expressions.The signature of
if(expression){ JavaScript if else if statement is given below.
//content to be evaluated if(expression1){
//content to be evaluated if expression1 is true
} }
<script> else if(expression2){
var a=20; //content to be evaluated if expression2 is true
if(a>10){ }
document.write("value of a is greater than 10"); else if(expression3){
} //content to be evaluated if expression3 is true
</script> }
else{
JavaScript If...else Statement //content to be evaluated if no expression is true
It evaluates the content whether condition is
true of false. The syntax of JavaScript if-else }
statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
ITL501 - IP Lab 22
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It
makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
for loop
while loop
do-while loop
for-in loop
1) JavaScript For loop 2) JavaScript while loop 3) JavaScript do while loop
The JavaScript for loop iterates the The JavaScript while loop iterates The JavaScript do while
elements for the fixed number of the elements for the infinite loop iterates the elements for the
times. It should be used if number of number of times. It should be infinite number of times like
iteration is known. The syntax of for used if number of iteration is not while loop. But, code is executed
loop is given below. known. The syntax of while loop at least once whether condition is
is given below. true or false. The syntax of do
for (initialization; condition; increme while loop is given below.
nt) while (condition)
{ { do{
code to be executed code to be executed code to be executed
} } }while (condition);
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse
the code.
JavaScript Function Syntax
The syntax of declaring function is given below.
<script> <script>
function msg(){ function getcube(number){
alert("hello! this is message"); alert(number*number*number);
} }
</script> </script>
<input type="button" onclick="msg()" value="call fu <form>
nction"/> <input type="button" value="click" onclick="getcube(
4)"/>
</form>
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.There are 3 ways
to construct array in JavaScript
By array literal
By creating instance of Array directly (using new keyword)
By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
<script>
var emp=["Sonoo","Vimal","Ratan"];
ITL501 - IP Lab 23
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
3) JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that we don't have to
provide value explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
JavaScript String
The JavaScript string is an object that represents a sequence of characters.There are 2 ways to create string
in JavaScript
By string literal
By string object (using new keyword)
1) By string literal 2) By string object (using new keyword)
The string literal is created using double quotes. The The syntax of creating string object using new
syntax of creating string using string literal is given keyword is given below:
below: var stringname=new String("string literal");
var stringname="string value"; Here, new keyword is used to create instance of
string.
<script> <script>
var str="This is string literal"; var stringname=new String("hello javascript string");
document.write(str); document.write(stringname);
</script> </script>
ITL501 - IP Lab 25
Results:
Conclusion:
References:
1. HTML 5 Black Book (Covers CSS3, JavaScript, XML, XHTML, AJAX, PHP, jQuery) 2Ed., DT Editorial
Services
2. https://tutorialspoint.com/
3. https://www.javatpoint.com/
Industrial Applications:
JavaScript is used to create interactive websites. It is mainly used for:
Client-side validation,
Dynamic drop-down menus,
Displaying date and time,
Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),
Displaying clocks etc.
ITL501 - IP Lab 26
Questionnaire:
Q1. Which type of JavaScript language is ___
a) Object-Oriented b)Object-Based c) Assembly-language d) High-level
Q3. Which one of the following is the correct way for calling the JavaScript code?
a) Preprocessor b) Triggering Event c) RMI d) Function/Method
Q4. When there is an indefinite or an infinite value during an arithmetic computation in a program,
then JavaScript prints______.
a) Prints an exception error b) Prints an overflow error
c) Displays "Infinity" d) Prints the value as such
Q5. In the JavaScript, which one of the following is not considered as an error:
a) Syntax error b) Missing of semicolons c) Division by zero d) Missing of Bracket
Q6. Which of the following function of the String object returns the character in the string starting at
the specified position via the specified number of characters?
a) slice() b) split() c) substr() d) search()
Q8. Choose the correct snippet from the following to check if the variable "a" is not equal the
"NULL":
a) if(a!==null) b) if (a!) c) if(a!null) d)if(a!=null)
Q9. Suppose we have a text "human" that we want to convert into string without using the "new"
operator. Which is the correct way from the following to do so:
a) toString() b)String(human)
c)String newvariable="human" d) Both human.toString() and String(human)
Q10. Which one of the following operator returns false if both values are equal?
a) ! b)!== c)!= d) All of the above
ITL501 - IP Lab 27
Experiment No.5
JavaScript Classes, Object and Event Handling
Aim: Program based on JavaScript Classes, object and Event Handling.
Objective: To be able to implement JavaScript classes, objects and event handling.
Theory:
JavaScript Classes:
In JavaScript, classes are the special type of functions. We can define the class just like
function declarations and function expressions.
The JavaScript class contains various class members within a body including methods or
constructor. The class is executed in strict mode. So, the code containing the silent error or mistake
throws an error.
The class syntax contains two components:
Class declarations
Class expressions
Class Declarations
A class can be defined by using a class declaration. A class keyword is used to declare a class
with any particular name. According to JavaScript naming conventions, the name of the class always
starts with an uppercase letter.
Class Declarations Example
<script>
//Declaring class
class Employee
{
//Initializing an object
constructor(id,name)
{
this.id=id;
this.name=name;
}
//Declaring method
detail()
{
document.writeln(this.id+""+this.name+"<br>")
}
}
//passing object to a variable
var e1=new Employee(101,"Martin Roy");
var e2=new Employee(102,"Duke William");
e1.detail(); //calling method
e2.detail();
</script>
Class expressions
Another way to define a class is by using a class expression. Here, it is not mandatory to
assign the name of the class. So, the class expression can be named or unnamed. The class
expression allows us to fetch the class name. However, this will not be possible with class
declaration.
Unnamed Class Expression
The class can be expressed without assigning any name to it.
ITL501 - IP Lab 28
<script>
var emp = class {
constructor(id, name) {
this.id = id;
this.name = name;
}
};
document.writeln(emp.name);
</script>
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don't create class to get the object. But,
we direct create objects.
Creating Objects in JavaScript
There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1) JavaScript Object by object literal
The syntax of creating object using object literal is given below:
object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon).
Let’s see the simple example of creating object in JavaScript.
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+""+emp.name+""+emp.salary);
</script>
2) By creating instance of Object
The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
Let’s see the example of creating object directly.
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+""+emp.name+""+emp.salary);
</script>
3) By using an Object constructor
Here, you need to create function with arguments. Each argument value can be assigned in
the current object by using this keyword.
The this keyword refers to the current object.
The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
ITL501 - IP Lab 29
document.write(e.id+""+e.name+""+e.salary);
</script>
JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events which
represents that some activity is performed by the user or by the browser. When javascript code is included
in HTML, js react over these events and allow the execution. This process of reacting over the events is
called Event Handling. Thus, js handles the HTML events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute the task to be performed on
the event.
Some of the HTML events and their event handlers are:
Mouse events:
Event Performed Event Handler Description
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keyboard events:
Event Performed Event Handler Description
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:
Event Performed Event Handler Description
change onchange When the user modifies or changes the value of a form element
Window/Document events
Event Performed Event Handler Description
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the browser unloads it
resize onresize When the visitor resizes the window of the browser
ITL501 - IP Lab 30
Click Event
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is JavaTpoint");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>
MouseOver Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is JavaTpoint");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
Focus Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
//-->
</script>
</body>
</html>
Keydown Event
<html>
<head> Javascript Events</head>
ITL501 - IP Lab 31
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
Load event
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>
Results:
Conclusion:
References:
1. HTML 5 Black Book (Covers CSS3, JavaScript, XML, XHTML, AJAX, PHP, jQuery) 2Ed., DT Editorial
Services
2. https://tutorialspoint.com/
3. https://www.javatpoint.com/
Industrial Applications:
JavaScript is used to create interactive websites. It is mainly used for:
Client-side validation,
Dynamic drop-down menus,
Displaying date and time,
Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),
Displaying clocks etc.
ITL501 - IP Lab 32
Questionnaire:
Q1. Which of the following is the correct output for the following JavaScript code:
var x=5,y=1
var obj ={ x:10}
with(obj)
{
alert(y)
}
a) 1 b) Error c) 10 d)5
Q2. Which of the following number object function returns the value of the number?
a) toString() b) valueOf() c) toLocaleString() d) toPrecision()
Q4. Which one of the following is correct output for the following given JavaScript code:
function outputfun(object)
{
var place=object ?object.place: "Italy";
return "clean:"+ place;
}
console.log(outputfun({place:India}));
a) Error b) clean:Italy c) clean:India d) undefined
Q5. Which one of the following is correct output for the following given JavaScript code:
var obj=
{
length:20,
height:35,
}
if('breadth' in obj === false)
{
obj.breadth = 12;
}
console.log(obj.breadth);
a) Error b) Undefined c) 12 d) 20
Q6. A set of unordered properties that, has a name and value is called______
a) String b) Array c)Serialized Object d) Object
ITL501 - IP Lab 33
Q7. Every object contains three object attributes that are _______.
a) Prototype, class, object's extensible flag
b) Prototype, class, objects' parameters
c) Class, parameters, object's extensible flag
d) Native object, Classes and Interfaces and Object's extensible flag
Q8. Which one of the given options can be considered as a code equivalent to the following code?
var o =new Object();
a) var o= new Object; b) var o; c) var o = Object(); d) Object o=new Object();
Q10. Which one of the given options can be considered as the correct output for the following
JavaScript code?
const obj1 =
{
a:10,
b:15,
c:18
};
const obj2 =Object.assign({c:7, d:1}, obj1);
console.log(obj2.c, obj2.d);
a) Undefined b) 18,1 c) 7,1 d) Error
ITL501 - IP Lab 34
Experiment No. 6
JavaScript Form Validation
JavaScript provides a way to validate form's data on the client's computer before sending it to the
web server. Form validation generally performs two functions.
Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are
filled in. It would require just a loop through each field in the form and check for data.
Data Format Validation − Secondly, the data that is entered must be checked for correct form and
value. Your code must include appropriate logic to test correctness of data.
Username cannot be blank and has at least 3 characters and cannot be longer than 25
characters.
Email is mandatory and valid.
Password has eight characters or longer. And it must contain 1 lowercase character, 1
uppercase character, 1 number, and at least one special character in this set (!@#$%^&*).
The confirm password must be the same as the password.
ITL501 - IP Lab 35
Phone Number :In the Phone Number validation :
^ denotes starting of the string and it should be of type \d. That means it should contain
only digits from 0 to 9. Any non-digit characters will not be accepted under \d.
{10} denotes that length of the Digit characters should be exactly 10 only. No extra or
less characters will be permitted.
$ Denotes end of the string.
Country : Validation on Dropdown menu items :
If we have not selected any items from Drop-Down menu then it will prompt message
that “Please enter your country”. Because (-1) denotes that not any field is selected and
subsequent option items are considered as indices 0,1,2,3,4, and so on..
Gender : Check the radio button is selected or not
There are two ways in JavaScript to check the marked radio button or to identify which
radio button is selected. JavaScript offers two DOM methods for this.
o getElementById
o querySelector
The input radio checked property is used to check whether the checkbox is selected or
not. Use document.getElementById('id').checked method for this. It will return the checked status
of the radio button as a Boolean value. It can be either true or false.
True - If radio button is selected.
False - If radio button is not selected/ checked.
Course Registered: Checkbox validation
Results:
Conclusion:
References:
1. HTML 5 Black Book (Covers CSS3, JavaScript, XML, XHTML, AJAX, PHP, jQuery) 2Ed., DT
Editorial Services
2. https://tutorialspoint.com/
3. https://www.javatpoint.com/
Industrial Applications:
JavaScript is used to create interactive websites. It is mainly used for:
Client-side validation,
Dynamic drop-down menus,
Displaying date and time,
Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),
Displaying clocks etc.
ITL501 - IP Lab 36
Questionnaire:
Q1. In which part does the form validation occur?
a) Client b) Server c) Both Client and Server d) User side
Q2.What would happen if the data in the client had been wrong?
a) Sends back the data b) Waits for correction
c) Sends back the data and Waits for correction d) Returns the data instantly
Q7. How do you focus a particular part of the HTML page in JavaScript?
a) hover() b) focus() c) on() d) focuson()
Q9. Which class provides an interface for invoking JavaScript methods and examining JavaScript properties?
a. ScriptObject b. JSObject c. JavaObject d. Jobject
ITL501 - IP Lab 37
Experiment No.7
Installation of React and its components.
Aim: Installation and configuration of React and its components.
Objective:To install and configure React and its components.
Theory:
React JS -React is an open-source component-based front-end JavaScript library. It is used to create
fast and interactive user interfaces for web and mobile applications. It is easy to create a dynamic
application in React because it requires less coding and offer more functionality. It is used by big
MNC and fresh new startups
Features of React:
Reusable Components: A single React app consists of many components each component have their
own logic and code but we can easily reuse components any number of time hence reducing the
developers time and increasing the efficiency of work
Debugging: React app can be easily debug using “react developer tools”. It’s a browser extension
that can be used for both chrome as well as Firefox.
Introduction to Node.js and NPM on Windows 10
To run ReactJS we will require Node.js on our system. Node.js is a server which will help us
to run the React code. It is based on non-blocking input and output and the Chrome V8 JavaScript
engine. The Node.js code is open source.
NPM which is an abbreviation of Node package manager, npmjs.com is supported by various
developers around the world. It has various node modules, using which developers can host and
publish their modules on the open-source community. It hosts modules in private and public
visibility. A module carries code which exists to serve high or low level functionalities. In terms of
code adoption and availability of various modules it gives an edge and tries to make the developer
more productive.
While building an application, a developer can pick the module, tweak and remix it to suit the
application needs, and can then release to the open-source community. So, instead of reinventing the
wheel, it is like picking a wheel (npm module) from npmjs.com, giving it further momentum and
giving it back to the open source community.
Installation Reactjs on Windows:
Step 1: Install Node.js installer for windows. Click on this link. Here install the LTS version (the one
present on the left). Once downloaded open NodeJS without disturbing other settings, click on
the Next button until it’s completely installed.
ITL501 - IP Lab 38
Install the 14.18.1 LTS
After the download is complete we will go to the downloads folder and run the installer.
The installer will show the below Setup Wizard. Click next.
The next screen will ask for the End-user License Agreement. Select the checkbox at the bottom
right to provide your consent and click on Next to proceed with the installation.
The installer will ask for Destination folder and the default path set by installation is C:\Program
Files\nodejs\
Click on Next button
ITL501 - IP Lab 39
The above screen is an important step in the installation process. And if you see closely it also sets
the environmental path variables to command prompt on Windows.
Click on Next to continue with the installation.
The Windows OS may ask you to allow Node.js installation and make changes.Click on Yes button.
During the installation, if you have allowed for Chocolatey and required modules installation for
C++ and Python, you will see the UI below in the command prompt. This installation requires 3 Gb
of free disk space. In this tutorial this step is not required, so we are skipping this step by closing the
window.
If you are interested in installing it, press Enter to continue.
ITL501 - IP Lab 40
Once the installation is complete you need to verify the Node.js installation.
For this, we will use the command prompt.
To run command prompt
Press keys Win+R
And type cmd in the window below.
Next Click on Ok or Press Enter on the keyboard.
Step 2: Open command prompt to check whether it is completely installed or not type the command
–> node -v
After installation of Node.js, we need to install React. To check the Node.js version, open the
Windows command prompt.
Press Win+R and type cmd.
In the command line, type
node -v to see its version.
We can also check for npm version, which is installed with Node.js, with the following command
npm -v
After running these commands, we can check the node version v14.15.1 and npm version 6.14.8
As we have confirmed the Node.js installation we can proceed to the next steps.
Step 3: Now in the terminal run the below command:
npm install -g create-react-app
ITL501 - IP Lab 41
Installation will take few seconds
It will globally install react app for you. To check everything went well run the command
create-react-app --version
version 4.0.3
If everything went well it will give you the installed version of react app
Step 4:Now Create a new folder where you want to make your react app using the below command:
mkdir newfolder
Note: The newfolder in the above command is the name of the folder and can be anything.
ITL501 - IP Lab 42
Step 5: Now inside this folder run the command –>
Step 6: Now open the IDE of your choice for eg. Visual studio code and open the folder where you
have installed the react app newolder (in the above example) inside the folder you will see your
app’s name reactapp (In our example). Use the terminal and move inside your app name folder.Use
command cd reactapp (your app name)
ITL501 - IP Lab 43
Step 7: To start your app run the below command :
npm start
Once you run the above command a new tab will open in your browser showing React logo as shown
below :
Congratulation you have successfully installed the react-app and are ready to build awesome
websites and app
Results:
Conclusion:
References:
1. Learning React Functional Web Development with React and Redux, Alex Banks and Eve
Porcello,O’Reilly
2. https://www.tutorialspoint.com/
3. https://reactjs.org/tutorial/tutorial.html
ITL501 - IP Lab 44
Industry Applications:
the WhatsApp uses ReactJS for building user interfaces from Facebook, just like it uses
Underscore.
Amazon uses React.
React Native for Web is currently used in production Web apps by companies including
Twitter, Flipkart, Uber, and Major League Soccer.
ITL501 - IP Lab 45
Questionnaire:
Q1. Which of the following is the correct name of React.js?
a) React b) React.js c) ReactJS d) All of the above
Q5. A class is a type of function, but instead of using the keyword function to initiate it, which
keyword do we use?
a) Constructor b) Class c) Object d) DataObject
ITL501 - IP Lab 46
Experiment No.8
React Props, State, and Forms
Props are immutable so we cannot modify the props from inside the component. Inside the
components, we can add attributes called props. These attributes are available in the component as
this.props and can be used to render dynamic data in our render method.
Example: App.js
import React, { Component } from 'react';
class App extends React.Component {
render() {
return (
<div>
<h1> Welcome to { this.props.name } </h1>
<p><h4> Javatpoint is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad
and Faridabad. </h4></p>
</div>
);
}
}
export default App;
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
Default Props: It is not necessary to always add props in the reactDom.render() element. You can
also set default props directly on the component constructor. It can be explained in the below
example.
Example : App.js
import React, { Component } from 'react';
class App extends React.Component {
render() {
return (
<div>
<h1>Default Props Example</h1>
<h3>Welcome to {this.props.name}</h3>
ITL501 - IP Lab 47
<p>Javatpoint is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and
Faridabad.</p>
</div>
);
}
}
App.defaultProps = {
name: "JavaTpoint"
}
export default App;
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App/>, document.getElementById('app'));
State and Props: It is possible to combine both state and props in your app. You can set the state in
the parent component and pass it in the child component using props. It can be shown in the below
example.
Example: App.js
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "JavaTpoint",
}
}
render() {
return (
<div>
<JTP jtpProp = {this.state.name}/>
</div>
);
}
}
class JTP extends React.Component {
render() {
return (
<div>
<h1>State & Props Example</h1>
<h3>Welcome to {this.props.jtpProp}</h3>
<p>Javatpoint is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and
Faridabad.</p>
</div>
);
}
}
export default App;
ITL501 - IP Lab 48
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App/>, document.getElementById('app'));
React State
The state is an updatable structure that is used to contain data or information about the
component. The state in a component can change over time. The change in state over time can
happen as a response to user action or system event. A component with the state is known as stateful
components. It is the heart of the react component which determines the behavior of the component
and how it will render. They are also responsible for making a component dynamic and interactive.
A state must be kept as simple as possible. It can be set by using the setState() method and
calling setState() method triggers UI updates. A state represents the component's local state or
information. It can only be accessed or modified inside the component or by the component directly.
To set an initial state before any interaction occurs, we need to use the getInitialState() method.
For example, if we have five components that need data or information from the state, then
we need to create one container component that will keep the state for all of them.
Defining State
To define a state, you have to first declare a default set of values for defining the component's
initial state. To do this, add a class constructor which assigns an initial state using this.state. The
'this.state' property can be rendered inside render() method.
Example
The below sample code shows how we can create a stateful component using ES6 syntax.
import React, { Component } from 'react';
class App extends React.Component {
constructor() {
super();
this.state = { displayBio: true };
}
render() {
const bio = this.state.displayBio ? (
<div>
<p><h3>Javatpoint is one of the best Java training institute in Noida, Delhi, Gurugram, G
haziabad and Faridabad. We have a team of experienced Java developers and trainers from multinatio
nal companies to teach our campus students.</h3></p>
</div>
) : null;
return (
<div>
<h1> Welcome to JavaTpoint!! </h1>
{ bio }
</div>
);
}
}
export default App;
To set the state, it is required to call the super() method in the constructor. It is because
this.state is uninitialized before the super() method has been called.
ITL501 - IP Lab 49
Changing the State
We can change the component state by using the setState() method and passing a new state
object as the argument. Now, create a new method toggleDisplayBio() in the above example and bind
this keyword to the toggleDisplayBio() method otherwise we can't access this inside
toggleDisplayBio() method.
this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
Example
In this example, we are going to add a button to the render() method. Clicking on this button
triggers the toggleDisplayBio() method which displays the desired output.
React Forms
Forms are an integral part of any modern web application. It allows the users to interact with
the application as well as gather information from the users. Forms can perform many tasks that
depend on the nature of your business requirements and logic such as authentication of the user,
adding user, searching, filtering, booking, ordering, etc. A form can contain text fields, buttons,
checkbox, radio button, etc.
ITL501 - IP Lab 50
Creating Form
React offers a stateful, reactive approach to build a form. The component rather than the
DOM usually handles the React form. In React, the form is usually implemented by using controlled
components.
There are mainly two types of form input in React.
1. Uncontrolled component
2. Controlled component
Uncontrolled component
The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself
handles the form data. Here, the HTML elements maintain their own state that will be updated when
the input value changes. To write an uncontrolled component, you need to use a ref to get form
values from the DOM. In other words, there is no need to write an event handler for every state
update. You can use a ref to access the input field value of the form from the DOM.
Example
In this example, the code accepts a field username and company name in an uncontrolled component.
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.updateSubmit = this.updateSubmit.bind(this);
this.input = React.createRef();
}
updateSubmit(event) {
alert('You have entered the UserName and CompanyName successfully.');
event.preventDefault();
}
render() {
return (
<form onSubmit={this.updateSubmit}>
<h1>Uncontrolled Form Example</h1>
<label>Name:
<input type="text" ref={this.input} />
</label>
<label>
CompanyName:
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;
Controlled Component
In HTML, form elements typically maintain their own state and update it according to the
user input. In the controlled component, the input form element is handled by the component rather
than the DOM. Here, the mutable state is kept in the state property and will be updated only
with setState() method.
Controlled components have functions that govern the data passing into them on
every onChange event, rather than grabbing the data only once, e.g., when you click a submit button.
This data is then saved to state and updated with setState() method. This makes component have
better control over the form elements and data.
ITL501 - IP Lab 51
A controlled component takes its current value through props and notifies the changes
through callbacks like an onChange event. A parent component "controls" this changes by handling
the callback and managing its own state and then passing the new values as props to the controlled
component. It is also called as a "dumb component."
Example
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('You have submitted the input successfully: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<h1>Controlled Form Example</h1>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;
Results:
Conclusion:
References:
1. Learning React Functional Web Development with React and Redux, Alex Banks and Eve
Porcello,O’Reilly
2. https://www.tutorialspoint.com/
3. https://reactjs.org/tutorial/tutorial.html
Industry Applications:
The WhatsApp uses ReactJS for building user interfaces from Facebook, just like it uses
Underscore.
Amazon uses React.
React Native for Web is currently used in production Web apps by companies including
Twitter, Flipkart, Uber, and Major League Soccer.
ITL501 - IP Lab 53
Questionnaire:
Q1. Which of the following acts as the input of a class-based component?
a) Class b) Factory c) Render d) Props
Q3. How many numbers of elements a valid react component can return?
a) 1 b) 2 c) 4 d) 5
Q6. Which of the following is used to pass data to a component from outside in React.js?
a) SetState b) Render with arguments c) Props d) PropTypes
Q7. Which of the following function is used to change the state of the React.js component?
a) this.setState b) this.setChangeState c) this.State{} d) None of the above.
Q8. Which of the following statement is true for controlled components in React.js?
a) The source of truth is DOM. b) The source of truth can be anything.
c) The source of truth is a component state. d) None of the above.
Q9. What changes would appear in the component as soon as the state of the React component is changed?
a) It will do nothing; you have to call render method to render the component again.
b) It will re-render the component.
c) It can be created again from scratch.
d) None of the above.
ITL501 - IP Lab 54
Experiment No.9
React Events
Aim: Program on React Events.
Objective: To learn and implement event handling in React. Create a form that has an input and a
button. An event will be triggered when a value is entered. The button is used to call a function
which will reverse that value.
Theory:
React Events:
An event is an action that could be triggered as a result of the user action or system generated
event. For example, a mouse click, loading of a web page, pressing a key, window resizes, and other
interactions are called events.
Now we will look at certain rules to keep in mind while creating events in React.
camelCase Convention: Instead of using lowercase we use camelCase while giving names
of the react events. That simply means we write ‘onClick’ instead of ‘onclick’.
Pass the event as a function: In React we pass a function enclosed by curly brackets as the
event listener or event handler, unlike HTML where we pass the event handler or event
listener as a string.
Prevent the default: Just returning false inside the JSX element does not prevent the
default behavior in react. Instead, we have to call the ‘preventDefault’ method directly
inside the event handler function.
Syntax:
function Component(){
doSomething(e){
e.preventDefault();
// Some more response to the event
}
return (
<button onEvent={doSomething}></button>
);
}
Now after watching the above syntax, a question must come in, that what is the ‘e’ object, and
from where does it come from. Actually, ‘e’ is a synthetic event. This is an object made with a
wrapper around the actual event of the browser. This object is cross-browser.
Step 2: After creating the react application move to the directory as per your app name using the
following command:
cd name_of_the_app
Project Structure: Now open your application folder in an editor. You will see the following file
structure:
ITL501 - IP Lab 55
Approach: Now modify the default App.js file inside your source code directory according to the
following steps:
Make sure that React is imported. And also import the ‘App.css’ file as it contains some
CSS styles for the app component.
Clear everything written inside the <div> with ‘className’ App.
Create a heading and a button inside this div.
Create an onClick event inside the button and pass the ‘eventHandler’ function inside it. We
define the function at the top of the ‘App’ component.
Add the alert inside the function so that we can listen to the event and generate an alert
whenever the event occurs.
Example:
App.js
functionApp() {
functioneventHandler(){
alert('React is best to learn and do frontend coding!!!...' );
}
return(
<div className='App'>
<h1>Welcome to React</h1>
<button onClick={eventHandler}>Click foralert!</button>
</div>
);
}
export defaultApp;
Step to run the application: Open the terminal and write the following command in your
terminal.
npm start
ITL501 - IP Lab 56
Results:
Conclusion:
References:
1.Learning React Functional Web Development with React and Redux, Alex Banks and Eve
Porcello,O’Reilly
2. https://www.tutorialspoint.com/
3. https://reactjs.org/tutorial/tutorial.html
Industry Applications:
the WhatsApp uses ReactJS for building user interfaces from Facebook, just like it uses
Underscore.
Amazon uses React.
React Native for Web is currently used in production Web apps by companies including
Twitter, Flipkart, Uber, and Major League Soccer.
ITL501 - IP Lab 57
Questionnaire:
Q1. What is a React event?
Q2. List different rules to keep in mind while creating events in React.
Q3. What are the handling events with react have syntactic differences from handling events on
DOM?
Q7. What is true for the keys given to a list of elements in React?
ITL501 - IP Lab 58
Experiment No.10
Installation and configuration of Node.js.
Select “Next”
ITL501 - IP Lab 59
After clicking “Next”, End-User License Agreement (EULA) will open.
Destination Folder
Set the Destination Folder where you want to install Node.js & Select “Next”
ITL501 - IP Lab 60
Custom Setup
Select “Next”
Select “Install”
ITL501 - IP Lab 61
NOTE :
A prompt saying – “This step requires administrative privileges” will appear.
Authenticate the prompt as an “Administrator”
Installing Node.js.
Do not close or cancel the installer until the install is complete
Complete the Node.js Setup Wizard.
Click “Finish”
ITL501 - IP Lab 62
Step 3: Verify that Node.js was properly installed or not.
To check that node.js was completely installed on your system or not, you can run the
following command in your command prompt or Windows Powershell and test it:-
C:\Users\Admin> node -v
If node.js was completely installed on your system, the command prompt will print the
version of the node.js installed.
Console based Node.js Application: The Node.js console-based applications are run using Node.js
command prompt. Console module in Node.js provide a simple debugging console. Node.js is a
global console which can be used for synchronous as well as asynchronous communication. The
console.log() function is used to display output on console. This function prints output to stdout with
newline.
Syntax:
console.log([data][, ...]);
Here, data is the content to be displayed on console.
Example 1: Creating a Hello World application using Node.js. Create a geeks.js file containing the
following code:
console.log('Hello World');
ITL501 - IP Lab 63
Run the file on Node.js command prompt using command node geeks.js i.e. node <file_name> .
Output:
Example 2: Creating a Hello World application receiving the user input. Create a gfg.js file
containing the following code.
console.log(process.argv.slice(2));
The process.argv is used to provide command line argument to a program. Use the slice function
with 2 as its argument to get all the elements of argv that comes after its second element, i.e. the
arguments the user entered The first argument is location of the Node.js binary which runs the
program and the second argument is location of the file being run.
Output:
Web-based Node.js Application: A web-based Node.js application consists of the following three
important components:
Import required modules: Load Node.js modules using the require directive.
Load http module and store returned HTTP instance into a variable.
Syntax:
var http = require("http");
Create server: Create a server to listen the client’s requests. Create server instance
using createServer() method. Bind server to port 8080 using listen method associated with
server instance.
Syntax:
http.createServer().listen(8080);
Read request and return response: Read the client request made using browser or console and
return the response. A function with request and response parameters is used to read client
request and return response.
Syntax:
http.createServer(function (request, response) {...}).listen(8080);
Example: This example create a Hello World web-based application using Node.js. Create a
firstprogram.js file containing the following code.
ITL501 - IP Lab 64
http.createServer(function (req, res) {
// HTTP Status: 200 : OK
// Content Type: text/html
res.writeHead(200, {'Content-Type': 'text/html'});
// Send the response body as "Hello World!"
res.end('Hello World!');
}).listen(8080);
Run the file on Node.js command prompt using command node firstprogram.js and
type http://127.0.0.1:8080/ in a web browser to see the output.
Output:
Results:
Conclusion:
References:
1. Learning Node.js Development, Andrew Mead, Packt Publishing
2. https://www.geeksforgeeks.org/installation-of-node-js-on-windows/?ref=lbp
Industry Applications:
the WhatsApp uses ReactJS for building user interfaces from Facebook, just like it uses
Underscore.
Amazon uses React.
React Native for Web is currently used in production Web apps by companies including
Twitter, Flipkart, Uber, and Major League Soccer.
ITL501 - IP Lab 65
Questionnaire:
Q1. What is node.js?
Q5. Which of the following statement is used to execute the code of the sample.js file?
a) sample.js b) node sample.js c) nodejs sample.js d) None of the above.
Q8. Which of the following tool is used to automate the various tasks of the Node.js application?
a) Express.js b) GruntJS c) NPM d) None of the above
Q10. Which of the following is the correct syntax to initiate the Node.js File?
a) filename.js b) javascript filename.js c) node filename.js d) node filename
ITL501 - IP Lab 66
Experiment No.11
Node.js Callbacks, and Event loops
var fs = require("fs");
var filedata = fs.readFileSync('input.txt');
console.log(filedata.toString());
console.log("End of Program execution");
Now run the main.js to see the result with the following command:
node main.js
Explanation: In this example, we have an fs module of nodeJS that provides the functionality of
File I/O operations. With the help of the readFileSync() function, we are able to use the
Synchronous approach here, which is also called blocking functions as it waits for each instruction
to be complete first before going to the next one. Hence in this example, the function blocks the
program until it reads the file and then went ahead with the end of the program.
ITL501 - IP Lab 67
Output:
GFG
Example 2: Code for reading a file asynchronously in Node.js. Keep the “input.txt” file the same
as before. Here is the code of main.js:
main.js
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("End of Program execution");
Now run the main.js to see the result with the following command:
node main.js
Explanation: With the help of the readFile() function, we are able to use the Asynchronous
approach here, which is also called non-blocking functions as it never waits for each instruction to
complete, rather it executes all operations in the first go itself. Hence in this example, the function
runs in the background, and the control is returned to the next instruction. When the background
task is completed callback function is called.
Output:
GFG
Events
Each action on the computer is called an event. In nodeJS objects can fire events.
According to the official documentation of Node.js, it is an asynchronous event-driven JavaScript
runtime. Node.js has an event-driven architecture that can perform asynchronous tasks. Node.js has
an ‘events’ module that emits named events that can cause corresponding functions or callbacks to
be called. Functions(Callbacks) listen or subscribe to a particular event to occur and when that
event triggers, all the callbacks subscribed to that event are fired one by one in order to which they
were registered.
The EventEmmitter class: All objects that emit events are instances of the EventEmitter class. The
event can be emitted or listened to an event with the help of EventEmitter.
Syntax:
const EventEmitter=require('events');
var eventEmitter=new EventEmitter();
ITL501 - IP Lab 68
The following table lists all the important methods of the EventEmitter class:
It removes all the listeners from the array who are subscribed
eventEmitter.removeAllListeners() to the mentioned event.
eventEmitter.prependOnceListener() It will add the one-time listener to the beginning of the array.
ITL501 - IP Lab 69
Example 1: Code for creating a program of a simple event:
main.js
Now run the main.js to see the result with the following command:
node main.js
Output:
Example 2: This example, shows the creating and removing of the listener. The EventEmitter
instance will emit its own ‘newListener’ event. The ‘removeListener’ event is emitted after a
listener is removed.
main.js
// Importing events
const EventEmitter = require('events');
// Register to newListener
eventEmitter.on( 'newListener', (event, listener) => {
console.log(`The listener is added to ${event}`);
});
// Register to removeListener
eventEmitter.on( 'removeListener', (event, listener) => {
console.log(`The listener is removed from ${event}`);
});
ITL501 - IP Lab 70
console.log("Message from fun2: " + msg);
};
// Removing listener
eventEmitter.off('myEvent', fun1);
// Triggering myEvent
eventEmitter.emit('myEvent', 'Event occurred');
Now run the main.js to see the result with the following command:
node main.js
Output:
Results:
Conclusion:
References:
1. Learning Node.js Development, Andrew Mead, Packt Publishing
2. https://www.geeksforgeeks.org/installation-of-node-js-on-windows/?ref=lbp
1. Web Development with Node and Express, Ethan Brown, O’Reilly
Industry Applications:
Paypal
LinkedIn
Yahoo
Mozilla
Netflix
Uber
Groupon
GoDaddy
eBay
ITL501 - IP Lab 71
Questionnaire:
Q1. Which of the following statement is correct?
a) js is Server Side Language. b) js is the Client Side Language.
c) js is both Server Side and Client Side Language. d) None of the above.
Q3. Which of the following command is used to install the Node.js express module?
a) $ npm install express b) $ node install express c) $ install express d) None of the above
Q5. Which of the following extension is used to save the Node.js files?
a) .js b) .node c) .java d) .txt
Q7. Which of the following method of fs module is used to get file information?
a) fs.open(path, flags[, mode], callback) b) fs.stat(path, callback)
c) fs.readFile(path, flags[, mode], callback) d) None of the above.
ITL501 - IP Lab 72
Experiment No.12
Express app
ITL501 - IP Lab 73
Step 2: Install necessary dependencies for our application.
npm install express
Something like this will be shown on successful installation,
Create a file app.js, for this article, we will write the whole express code in that file. This will be our
folder structure. Now Inside app.js, Import express with require keyword and create an app by
calling the express() function provided by the express framework. Set the port for our local
application, 3000 is the default but you can choose any according to the availability of ports. Call
the listen() function, It requires path and callback as an argument. It starts listening to the connection
on the specified path, the default host is localhost, and our default path for the local machine is
the localhost:3000, here 3000 is the port which we have set earlier. The callback function gets
executed either on the successful start of the server or due to an error.
app.js
Step to run the application: Now as we have created a server we can successfully start running it
to see it’s working, write this command in your terminal to start the express server.
node app.js
Output: You will see something like this on the terminal.
ITL501 - IP Lab 74
Now with all of this, we have created and run the server successfully, if your server is not starting
then there may be some error, try to analyze and read that error and resolve it accordingly.
Finally, after a successful run if you try to open the URL (localhost:3000) on the browser it will
show you cannot GET / because we have not configured any route on this application yet.
Step 4: Now we will set all the routes for our application.
Routes are the endpoints of the server, which are configured on our backend server and whenever
someone tries to access those endpoints they respond accordingly to their definition at the backend.
If you’re a beginner you can consider route as a function that gets called when someone requests the
special path associated with that function and return the expected value as a response. We can create
routes for HTTP methods like get, post, put, and so on.
Syntax: The basic syntax of these types of routes looks like this, the given function will execute
when the path and the request method resemble.
app.anyMethod(path, function)
Example 1: Setting up a basic get request route on the root URL (‘/’ path) of the server.
With app.get() we are configuring our first route, it requires two arguments first one is the
path and, the second one is a function that will be executed when anyone requests this path with GET
method. The express provides the request and response object as a parameter to all such types of
functions.
The req is a giant object which will be received from the user and res is an object which will
be sent to the user after the function finishes execution.
Later we are calling status() method it takes an HTTP status code as an argument and when
the response is returned, the status will be sent along.
Finally, we are returning the response to the user. The send() method takes a string, object,
array, or buffer as an argument and is used to send the data object back to the client as an HTTP
response, also there are lots of types of response in express like res.json() which is used to send
JSON object, res.sendFile() which is used to send a file, etc.
app.js
Step to run the application: Save this code, restart the server, and open the localhost on the given
port. When client request with the appropriate method on the specified path ex: GET request on ‘/’
path, our function is returning the response as plain text If we open the network section in chrome
developers tools (press Ctrl+Shift+I to open) we will see the response returned by the localhost along
with all information.
ITL501 - IP Lab 75
Output:
Example 2: Setting up one more get request route on the ‘/hello’ path.
Most of the things are the same as the previous example.
The set() function is used to set HTTP header’s content type as HTML. When the browser receives
this response it will be interpreted as HTML instead of plain text.
Also in this example, we are not explicitly setting status, it is now concatenated with the statement of
sending the response. This is another way to send status along with a response.
app.js
Step to run the application: Save this code, restart the server, and open the localhost on the given
port. Now access the ‘/hello’ route from the browser, The h1 text inside HTML will be shown as a
response.
Output:
ITL501 - IP Lab 76
Step 5: Now we will see how to send data to server.
Sometimes we have to send our data to the server for processing, for example when you try to
log in on Facebook you send a password and email to the server, Here we will see how to receive
data from the user request. We can send data with the request object on the specified path with
appropriate HTTP methods. Till now we were using the browser to interact with the server, but in
this step, any tool or frontend form is must be needed to send data because the browser search bar
can only send get requests to receive resources from the server.
Example: Setting up a route to be accessed by users to send data with post requests.
Before creating a route for receiving data, we are using an inbuilt middleware, Middleware is such a
broad and more advanced topic so we are not going to discuss it here, just to understand a little bit
you can think of this as a piece of code that gets executed between the request-response cycles.
The express.json() middleware is used to parses the incoming request object as a JSON
object. The app.use() is the syntax to use any middleware.
After then we have created a route on path ‘/’ for post request.
const {name}, which is the syntax in ES6 to extract the given property/es from the object.
Here we are extracting the name property which was sent by the user with this request object.
After that, we are simply sending a response to indicate that we have successfully received
data. If this `${} ` is looking weird to you then let me tell you that it is the syntax in ES6 to generate
strings with javascript expression in ES6. We can inject any javascript expression inside ${}.
app.js
app.use(express.json());
app.post('/', (req, res)=>{
const {name} = req.body;
res.send(`Welcome ${name}`);
})
Step to run the application: We are Accessing the route with Postman. It is a tool to test APIs, we
can use any other things like Axios, fetch, or any other thing from the frontend or cURL from the
terminal, but that will make you divert from the topic, just keep in mind that our express server only
demands a path with request object it doesn’t matter from where it is coming. We have sent the data
as a JSON object with the request body and express is sending a response back to us along with the
data. It indicates that our goal to send data to the server succeeded.
ITL501 - IP Lab 77
Output:
ITL501 - IP Lab 78
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'Static Files')))
Step to run the application: This will be the returned response when we request some static file
from the directory which we are serving as static. Here you can see we have received an HTML file
as a response for ‘/static/random.html’. The same things happen when we request
for ‘/static/1.jpg’.
Output:
ITL501 - IP Lab 79
res.sendFile(path.join(__dirname,'image.jpg'));
});
Output: After running the server, When we request the route ‘/file’ the server sends the image.jpg
file as a response.
Results:
Conclusion:
References:
1. Web Development with Node and Express, Ethan Brown, O’Reilly
2. https://www.javatpoint.com/expressjs-tutorial
Industry Applications:
Paypal
LinkedIn
Yahoo
Mozilla
Netflix
Uber
Groupon
GoDaddy
eBay
ITL501 - IP Lab 80
Questionnaire:
Q1. Who is credited as the developer of Express.js?
a) Larry wall b) Rich Hickey c) TJ Holowaychuk d) Rob Pike
Q2. Which of the following are the core features of the Express framework?
a) It allows us to set up middleware to respond to HTTP Requests.
b) It defines a routing table that can work as per HTTP Method and URL.
c) It is used to render the HTML pages dynamically.
d) All of the above.
Q4. How is it possible to create chainable route handlers for a route path in Express.js?
a) Using app.route() b) Using app.routes() c) Using app.router() d) Using app.routing()
Q6. Which of the following is the correct syntax to use Express.js in Node?
a) var = require('express')(); b) var_require('express')();
c) var app = require('express')(); d) None of the above.
Q7. Which of the following command is used to check the current version of NPM?
a) nmp –ver b) npm –version c)npm help d) None of the above.
Q9. To use Mongo with Express.js, we need a client API for node.
a) TRUE b) FALSE c) can be true or false d) Cannot say
Q10. How is it possible to create chainable route handlers for a route path in Express.js?
a) Using app.route() b) Using app.routes() c) Using app.router() d) Using app.routing()
ITL501 - IP Lab 81