0% found this document useful (0 votes)
56 views90 pages

IP Lab - Final Lab Manual 2024-25

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 90

MGM’s College of Engineering and Technology

Kamothe, Navi Mumbai – 410209

Department of Information Technology

LAB MANUAL

Course name: IP Lab


(Subject Code: ITL501)

Year: Third Year (C Scheme)

Semester: V

Academic Year: 2024-25


CONTENTS

S.No. Topic PAGE NO.

1. Vision and Mission of college and department i


2. Examination Scheme and University Syllabus ii
3. Course Objectives iii
4. PSO & PO iv
5. CO & PO Mapping and CO & PSO Mapping vi
6. List of Experiments vii
7. Additional Experiments viii

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.

Department of Information Technology

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:

1. To orient students to HTML for making webpages.


2. To expose students to CSS for formatting web pages.
3. To expose students to developing responsive layout.
4. To expose students to JavaScript to make web pages interactive.
5. To orient students to React for developing front end applications.
6. To orient students to Node.js for developing backend applications.

Course Outcomes(CO):

Name of the course CO Lab outcome{LO}

Identify and apply the appropriate HTML tags to develop a


1 webpage.
Identify and apply the appropriate CSS tags to format data on
2 webpage
Construct responsive websites using Bootstrap
3
IP Lab 4 Use JavaScript to develop interactive web pages.

Construct front end applications using React


5
Construct back end applications using Node.js/Express
6

iii

ITL501 - IP Lab
Program Specific Outcomes (PSO)

PSO1 Analyze real life problems and design user friendly solutions.

To provide effective solutions for problems in sectors like healthcare, science,


PSO2 commerce, e-governance etc., by employing right set of tools and
methodologies.
PSO3 Design and implement right IT infrastructural setups for any organization.

Program Outcomes (PO)

Engineering Graduates will be able to:


PO1) Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.

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.

PO10) Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

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

CO & PSO Mapping:

Name of the course CO Code PSO1 PSO2 PSO3 MAP

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,

04 Operators, Conditions, Loops, Functions, CO4 PO1,PO2 PSO1 21


Arrays, String and Date.
Program based on JavaScript Classes,
05 CO4 PO1,PO2 PSO2 28
object and Event Handling.
Program for form validation using
06 CO4 PO1,PO2 PSO2 35
JavaScript.

Installation and configuration of React and


07 CO5 PO3 PSO2 38
its components.

08 Program on React Props, State, and Forms. CO5 PO3 PSO2 47

Program on React Events, Routers, Refs, PSO2


09 CO5 PO3,PO4 55
and Keys

10 Installation and configuration of Node.js. CO6 PO5 PSO3 59

Programs based on Node.js Callbacks, and


11 CO6 PO5 PSO2 67
Event loops

12 Creating express app. CO6 PO5 PSO3 73

Subject Incharge Lab Incharge HOD

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

Use <img> tag as a link


We can also link an image with other page or we can use an image as a link. To do this, put <img> tag inside the
<a> tag.
Example:
<a href="https://www.javatpoint.com/what-is-robotics"><img src="robot.jpg" height="100" width="100"></a>

 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>

<h2>Iframe - Target for a Link</h2>


<iframe height="300px" width="100%" src="new.html" name="iframe_a"></iframe>
<p><a href="https://www.javatpoint.com" target="iframe_a">JavaTpoint.com</a></p>
<p>The name of iframe and link target must have same value else link will not open as a frame. </p>

</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

allowfullscreen If true then that frame can be opened in full screen.


height Pixels It defines the height of the embedded iframe, and the default height is 150 px.
name text It gives the name to the iframe. The name attribute is important if you want to
create a link in one frame.
frameborder 1 or 0 It defines whether iframe should have a border or not. (Not supported in

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>

HTML Form Tags


Let's see the list of HTML 5 form tags.
Tag Description

<form> It defines an HTML form to enter inputs by the used side.


<input> It defines an input control.
<textarea> It defines a multi-line input control.
<label> It defines a label for an input element.
<fieldset> It groups the related element in a form.
<legend> It defines a caption for a <fieldset> element.
<select> It defines a drop-down list.
<optgroup> It defines a group of related options in a drop-down list.
<option> It defines an option in a drop-down list.

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

<datalist> It specifies a list of pre-defined options for input control.


<keygen> It defines a key-pair generator field for forms.
<output> It defines the result of a calculation.

HTML <input> element Label Tag in Form


The HTML <input> element is fundamental It is considered better to have label in form. As it makes
form element. It is used to create form fields, to take the code parser/browser/user friendly.
input from user. We can apply different input filed to If you click on the label tag, it will focus on the text
gather different information form user. Following is control. To do so, you need to have for attribute in label
the example to show the simple text input. tag that must be same as id attribute of input tag.
Example: <form>
<body> <label for="firstname">First Name: </label> <br/>
<form> <input type="text" id="firstname" name="firstna
Enter your name <br> me"/> <br/>
<input type="text" name="username"> <label for="lastname">Last Name: </label>
</form> <input type="text" id="lastname" name="lastnam
</body> e"/> <br/>
HTML TextField Control </form>
The type="text" attribute of input tag creates HTML Password Field Control
textfield control also known as single line textfield The password is not visible to the user in password field
control. The name attribute is optional, but it is control.
required for the server side component such as JSP, <form>
ASP, PHP etc. <label for="password">Password: </label>
<form> <input type="password" id="password" name="p
First Name: <input type="text" name="firstname"/> assword"/> <br/>
<br/> </form>
Last Name: <input type="text" name="lastname"/> HTML 5 Email Field Control
<br/> The email field in new in HTML 5. It validates the text for
</form> correct email address. You must use @ and . in this field.
HTML <textarea> tag in form <form>
The <textarea> tag in HTML is used to insert <label for="email">Email: </label>
multiple-line text in a form. The size of <textarea> <input type="email" id="email" name="email"/>
can be specify either using "rows" or "cols" attribute <br/>
or by CSS. </form>
Example: Radio Button Control
<!DOCTYPE html> The radio button is used to select one option from
<html> multiple options. It is used for selection of gender, quiz
<head> questions etc.
<title>Form in HTML</title> If you use one name for all the radio buttons, only one
</head> radio button can be selected at a time.
<body> Using radio buttons for multiple options, you can only
<form> choose a single option at a time.
Enter your address:<br> <form>
<textarea rows="2" cols="20"></textarea> <label for="gender">Gender: </label>
</form> <input type="radio" id="gender" name="gender"
</body> value="male"/>Male
</html> <input type="radio" id="gender" name="gender"
Checkbox Control value="female"/>Female <br/>
The checkbox control is used to check multiple </form>
options from given checkboxes. Example:
<form> <form>
Hobby:<br> <label for="name">Enter name</label><br>

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

2. Which of the following tags do not require a terminator?


a) <u>b) <br>c) <b>d) none of the mentioned

3. To get the ordered list we use


a) <h1>b) <ul>c) <ol>d) <ml>

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

6. _____ tag is used before beginning of the paragraph text


a) <textarea>b) <sup>c) <p>d) <h1>

7. html document have a extension ______


a) .htx or .htxlb) .htm or .htmlc) .hmt or hmtld) none of the mentioned

8. The components of multimedia are


A) Text, pictures, video, soundB) Text pictures, animation
C) Text, pictures, video, animation, soundD) 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

10. Which of the following is not a HTML5 tag?


a) <track>b) <video>c) <slider>d) <source>

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>

<meta name="viewport" content="width=device-width, initial-scale=1">


Note: The "width=device-width" part is used to set the width of the page to follow the screen-width
of the device (vary according to the devices).

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>

<button class="btn btn-default">default</button>


<button class="btn btn-primary">primary</button>
<button class="btn btn-danger">danger</button>
<button class="btn btn-success">success</button>
<button class="btn btn-info">info</button>
<button class="btn btn-warning">warning</button>
<button class="btn btn-link">Link</button>

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

<nav class="navbar navbar-default">


<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Page 1</a></li>
<li><a href="#">Page 2</a></li>
<li><a href="#">Page 3</a></li>
</ul>
</div>
</nav>

<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

Q2. Who developed the bootstrap?


a) James Gosling b) Mark Jukervich c) Dennis Ritchie d) Mark Otto and Jacob Thornton

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

Q4. How many columns are allowed in a bootstrap grid system?


a) 2 b)12 c) 3 d)5

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

Q6. The correct syntax of creating a standard navigation bar is -


a) <nav class="navigationbar navbar"> b) <nav class="navbar navbar-default">
c) <nav class="nav navbar"> d) <nav class="navbar default">

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

Q9. Which of the following is correct method to add a success button?


a) <button class = "btn btn-success"> success </button>
b) <button class = "btn button-success"> success </button>
c) <button class = "button btn-success"> success </button>
d) <button class = "button btn-primary"> success </button>

Q10.Which of the following class in Bootstrap is used to create a button as a link?


a) .btn-anchor b) .btn-link c) .btn-hyperlink d) None of the abov

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.

Objective: To understand the concept of 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:

Operator Description Example Operator Description Example

+ Addition 10+20 = 30 == Is equal to 10==20 = false

- Subtraction 20-10 = 10 === Identical (equal and of 10==20 = false


same type)
* Multiplication 10*20 = 200
!= Not equal to 10!=20 = true
/ Division 20/10 = 2
!== Not Identical 20!==20 = false
% Modulus 20%10 = 0
(Remainder) > Greater than 20>10 = true

++ 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

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift (10>>>2) = 2


with Zero

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.

function functionName([arg1, arg2, ...argN]){


//code to be executed
}
JavaScript Function Example JavaScript Function Arguments
Let’s see the simple example of function in We can call function by passing arguments. Let’s see
JavaScript that does not has arguments. the example of function that has one argument.

<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:

var arrayname=new Array();


Here, new keyword is used to create instance of array.
Let's see the example of creating array directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

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>

JavaScript String Methods


1) JavaScript String charAt(index) Method 2) JavaScript String concat(str) Method
The JavaScript String charAt() method returns the The JavaScript String concat(str) method
character at the given index. concatenates or joins two strings.
<script>
<script> var s1="javascript ";
var str="javascript"; var s2="concat example";
document.write(str.charAt(2)); var s3=s1.concat(s2);
</script> document.write(s3);
</script>
ITL501 - IP Lab 24
3) JavaScript String indexOf(str) Method 4) JavaScript String lastIndexOf(str) Method
The JavaScript String indexOf(str) method returns the The JavaScript String lastIndexOf(str) method returns
index position of the given string. the last index position of the given string.
<script> <script>
var s1="javascript from javatpoint indexof"; var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from"); var n=s1.lastIndexOf("java");
document.write(n); document.write(n);
</script> </script>
5) JavaScript String toLowerCase() Method 6) JavaScript String toUpperCase() Method
The JavaScript String toLowerCase() method returns The JavaScript String toUpperCase() method returns
the given string in lowercase letters. the given string in uppercase letters.
<script> <script>
var s1="JavaScript toLowerCase Example"; var s1="JavaScript toUpperCase Example";
var s2=s1.toLowerCase(); var s2=s1.toUpperCase();
document.write(s2); document.write(s2);
</script> </script>
7) JavaScript String slice(beginIndex, endIndex) 8) JavaScript String trim() Method
Method The JavaScript String trim() method removes leading
The JavaScript String slice(beginIndex, endIndex) and trailing whitespaces from the string.
method returns the parts of string from given
beginIndex to endIndex. In slice() method, <script>
beginIndex is inclusive and endIndex is exclusive. var s1=" javascript trim ";
<script> var s2=s1.trim();
var s1="abcdefgh"; document.write(s2);
var s2=s1.slice(2,5); </script>
document.write(s2);
</script>

JavaScript Date Object


The JavaScript date object can be used to get year, month and day. You can display a timer on
the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods to get and
set day, month, year, hour, minute and seconds.

JavaScript Date Example JavaScript Current Time Example


Let's see the simple example to print date object. Let's see the simple example to print current time
It prints date and time both. of system.
Current Date and Time: <span id="txt"></span>
<script> Current Time: <span id="txt"></span>
var today=new Date(); <script>
document.getElementById('txt').innerHTML=to var today=new Date();
day; var h=today.getHours();
</script> var m=today.getMinutes();
<script> var s=today.getSeconds();
var date=new Date(); document.getElementById('txt').innerHTML=h+"
var day=date.getDate(); :"+m+":"+s;
var month=date.getMonth()+1; </script>
var year=date.getFullYear();
document.write("<br>Dateis:
"+day+"/"+month+"/"+year);
</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

Q2. The "function" and " var" are known as:


a) Keywords b)Data types c)Declaration statements d) Prototypes

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()

Q7. In JavaScript the x===y statement implies that:


a) Both x and y are equal in value, type and reference address as well.
b) Both are x and y are equal in value only.
c) Both are equal in the value and data type. d)Both are not same at all.

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

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.

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

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element

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()

Q3. The "new Point(3,2)", is a kind of _______ expression


a) Object Creation Expression b) Primary Expression
c) Invocation Expression d) Constructor Calling Expression

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();

Q9. If the following lines of code differ, what is the difference?


Code A : !!(obj1 && obj2);
Code B : (obj1 && obj2);
a) The first line results in a realBoolean value whereas the second line merely checks for the
existence of the objects
b) Both the lines of code A and B will result in a Boolean value "False"
c) Both the lines of code A and B will check just for the existence of the object alone
d) Both the lines of code A and B will result in a Boolean value "True"

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

Aim: Program for form validation using JavaScript.


Objective: To validate the form by using Javascript
Theory:
Form validation normally used to occur at the server, after the client had entered all the necessary
data and then pressed the Submit button. If the data entered by a client was incorrect or was simply
missing, the server would have to send all the data back to the client and request that the form be
resubmitted with correct information. This was really a lengthy process which used to put a lot of
burden on the server.

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.

You’ll validate the following:

 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

Q3. What is the purpose of the basic validation?


a) Data correctness b) Mere data existence
c) Both Data correctness and Mere data existence d) Data modification

Q4.What is the purpose of data format validation?


a) Data correctnessb) Mere data existence
c) Both Data correctness and Mere data existenced) Data modification

Q5. Which is the function that is called to validate a data?


a) validate() b) valid() c) validation() d) no predefined function for data validation

Q6. How to find the index of a particular string?


a) position() b) index() c) indexOf() d) positionof()

Q7. How do you focus a particular part of the HTML page in JavaScript?
a) hover() b) focus() c) on() d) focuson()

Q8. How do we debug a script?


a.Use of JavaScript Validator b.Use of JavaScript Debugger
c.Use of JavaScript Validator & Debugger d.None of the mentioned

Q9. Which class provides an interface for invoking JavaScript methods and examining JavaScript properties?
a. ScriptObject b. JSObject c. JavaObject d. Jobject

Q10. What is the purpose of a JavaScript debugger?


a. Correction of errors b. Placing script execution under control
c. Correction of errors & Placing script execution under control d. None of the mentioned

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.

Move inside the same folder using the below command:

cd newfolder (your folder name)

ITL501 - IP Lab 42
Step 5: Now inside this folder run the command –>

create -react -app reactfirst YOUR_APP_NAME

It will take some time to install the required dependencies

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

Q2. Which of the following are the advantages of React.js?


a) React.js can increase the application's performance with Virtual DOM.
b) React.js is easy to integrate with other frameworks such as Angular, BackboneJS since it is only a
view library.
c) React.js can render both on client and server side.
d) All of the above

Q3. Which of the following is not a disadvantage of React.js?


a) React.js has only a view layer. We have put your code for Ajax requests, events and so on.
b) The library of React.js is pretty large.
c) The JSX in React.js makes code easy to read and write.
d) The learning curve can be steep in React.js.

Q4. Which of the following command is used to install create-react-app?


a) npm install -g create-react-app b) npm install create-react-app
c) npm install -f create-react-app d) install -g create-react-app

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

Q6. How to execute React files?

Q7. What are the features of React?

Q8. What is Node.js?

Q9. What is NPM?

Q10. Which command is used to run app?

ITL501 - IP Lab 46
Experiment No.8
React Props, State, and Forms

Aim: Program on React Props, State, and Forms.


Objective: To study the implementation of React props, state and forms.
Theory:
React Props
Props stand for "Properties." They are read-only components. It is an object which stores the value of
attributes of a tag and work similar to the HTML attributes. It gives a way to pass data from one
component to other components. It is similar to function arguments. Props are passed to the
component in the same way as arguments passed in a function.

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';

ReactDOM.render(<App name = "JavaTpoint!!" />, document.getElementById('app'));

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.

import React, { Component } from 'react';


class App extends React.Component {
constructor() {
super();
this.state = { displayBio: false };
console.log('Component this', this);
this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
}
toggleDisplayBio(){
this.setState({displayBio: !this.state.displayBio});
}
render() {
return (
<div>
<h1>Welcome to JavaTpoint!!</h1>
{
this.state.displayBio ? (
<div>
<p><h4>Javatpoint is one of the best Java training institute in Noida, Delhi, Guru
gram, Ghaziabad and Faridabad. We have a team of experienced Java developers and trainers from m
ultinational companies to teach our campus students.</h4></p>
<button onClick={this.toggleDisplayBio}> Show Less </button>
</div>
):(
<div>
<button onClick={this.toggleDisplayBio}> Read More </button>
</div>
)
}
</div>
)
}
}
export default App;

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;

Handling Multiple Inputs in Controlled Component


If you want to handle multiple controlled input elements, add a name attribute to each
element, and then the handler function decided what to do based on the value of event.target.name.
Example
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
personGoing: true,
numberOfPersons: 5
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
ITL501 - IP Lab 52
this.setState({
[name]: value
});
}
render() {
return (
<form>
<h1>Multiple Input Controlled Form Example</h1>
<label>
Is Person going:
<input
name="personGoing"
type="checkbox"
checked={this.state.personGoing}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Number of persons:
<input
name="numberOfPersons"
type="number"
value={this.state.numberOfPersons}
onChange={this.handleInputChange} />
</label>
</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

Q2. Which of the following keyword is used to create a class inheritance?


a) Create b) Inherits c) Extends d) This

Q3. How many numbers of elements a valid react component can return?
a) 1 b) 2 c) 4 d) 5

Q4. What is a state in React?


a) A permanent storage. b) Internal storage of the component.
c) External storage of the component. d) None of the above.

Q5.What are the two ways to handle data in React?


a) State & Props b) Services & Components c) State & Services d) State & Component

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.

Q10. What are the two types of form input in React?

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.

Creating react application:

Step1:Create a React application using the following command:

npx create-react-app name_of_the_app

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

import React from 'react';

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?

Q4. What is the use of preventDefault() function in React ?

Q5. What are the mouse events supported by React?

Q6. What are the keyboard events supported by React?

Q7. What is true for the keys given to a list of elements in React?

a. Unique in the DOM.


b. Unique among the siblings only.
c. Do not require to be unique.
d. None of the above.

Q8. What are the form events supported by React?

Q9. What are the focus events supported by React?

Q10. What are the image events supported by React?

ITL501 - IP Lab 58
Experiment No.10
Installation and configuration of Node.js.

Aim: Installation and configuration of Node.js.


Objective: Installation and configuration of Node.js.
Theory:
Setting up the Node Development Environment
The Node can be installed in multiple ways on a computer. The approach used by you
depends on the existing development environment in the system. There are different package
installer for different environments. You can install Node by grabbing a copy of the source code and
compiling the application. Another way of installing Node is by cloning the GIT repository in all the
three environments and then installing it on the system.

Installing Node On Windows (WINDOWS 10):


You have to follow the following steps to install the Node.js on your Windows :
Step-1: Downloading the Node.js ‘.msi’ installer.
The first step to install Node.js on windows is to download the installer. Visit the official Node.js
website i.e) https://nodejs.org/en/download/ and download the .msi file according to your system
environment (32-bit & 64-bit). An MSI installer will be downloaded on your system.

Step-2: Running the Node.js installer.


Now you need to install the node.js installer on your PC. You need to follow the following steps for
the Node.js to be installed:-
 Double click on the .msi installer.

The Node.js Setup wizard will open.


Welcome To Node.js Setup Wizard.

Select “Next”

ITL501 - IP Lab 59
 After clicking “Next”, End-User License Agreement (EULA) will open.

Check “I accept the terms in the License Agreement”


Select “Next”

 Destination Folder

Set the Destination Folder where you want to install Node.js & Select “Next”

ITL501 - IP Lab 60
 Custom Setup

Select “Next”

 Ready to Install Node.js.

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.

Step 4: Updating the Local npm version.


The final step in node.js installed is the updation of your local npm version(if required) – the
package manager that comes bundled with Node.js.
You can run the following command, to quickly update the npm
npm install npm –global // Updates the ‘CLI’ client

Node.js First Application:


Node.js is an open source, cross-platform server environment which executes JavaScript
using V8 JavaScript Engine. Node.js helps to write front-end and back-end code in the same
language. It helps to write efficient code for real-time applications. In Node.js, the applications can
be written using console-based method or web-based method.

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.

// Require http header


var http = require('http');
// Create server

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?

Q2. How to update the npm?

Q3. What is the default scope in the Node.js application?


a) Global b) Local c) Global Function d) Local to object

Q4. Which of the following engine Node in core?


a) Chrome V8 b) Microsoft Chakra c) SpiderMonkey d) Node En

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.

Q6. Which of the following is not a valid language for Node.js?


a) JavaScript b) Java c) C d) C++

Q7. How many Node object methods are available?


a) 21 b) 18 c) 19 d) 20

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

Q9. Which of the following areas, Node.js, is not advised to be used?


a) Single Page Applications b) JSON APIs based Applications
c) CPU intensive applications d) Data-Intensive Real-time Applications (DIRT)

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

Aim: Programs based on Node.js Callbacks, and Event loops


Objective:
Theory:
Callbacks and Events in Node.js
 Callback Concept
A Callback is a function that is called automatically when a particular task is completed. The
Callback function allows the program to run other code until a certain task is not completed. The
callback function is heavily used in nodeJS. The callback function allows you to perform a large
number of I/O operations that can be handled by your OS without waiting for any I/O operation to
finish. It makes nodeJS highly scalable. For example: In Node.js, when a function starts reading a
file, It’s obviously going to take some time so without waiting for that function to complete, it
returns control to the execution environment immediately so to execute the succeeding instruction.
Once file I/O gets completed, the callback function will be automatically called hence there will be
no waiting or blocking for file I/O.
Note: The callback function is being replaced by async/await these days.
Syntax: Let’s see the syntax of the callback function.
const fs = require("fs");

fs.readFile("file_path", "utf8", function(err, data) {


if(err) {
// Handle the error
} else {
// Process the file text given with data
}
});
Example 1: Code for reading a file synchronously in Node.js. Create a text file input.txt with the
following text:
Welcome to GFG.
Learn NodeJS with GeeksforGeeks
Now, create a javascript file name main.js with the following code.
main.js

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:

EventEmitter Methods Description

eventEmmitter.on(event, listener) and


eventEmitter.addListener(event, listener) are pretty much
similar. It adds the listener at the end of the listener’s array
for the specified event. Multiple calls to the same event and
eventEmitter.addListener(event, listener will add the listener multiple times and
listener) && correspondingly fire multiple times. Both functions return
eventEmitter.on(event, listener) emitter, so calls can be chained.

It fires at most once for a particular event and will be


removed from listeners array after it has listened once.
eventEmitter.once(event, listener) Returns emitter, so calls can be chained.

Every event is named event in nodeJS. We can trigger an


eventEmitter.emit(event, [arg1], event by emit(event, [arg1], [arg2], […]) function. We can
[arg2], […]) pass an arbitrary set of arguments to the listener functions.

It takes two argument event and listener and removes that


eventEmitter.removeListener(event, listener from the listener’s array that is subscribed to that
listener) event

It removes all the listeners from the array who are subscribed
eventEmitter.removeAllListeners() to the mentioned event.

It will return the max listeners value set by


eventEmitter.getMaxListeners(n) setMaxListeners() or default value 10.

By default, a maximum of 10 listeners can be registered for


any single event. To change the default value for all
EventEmitter.defaultMaxListeners EventEmitter instances this property can be used.

eventEmitter.listeners(event) It returns an array of listeners for the specified event.

It returns the number of listeners listening to the specified


eventEmitter.listenerCount() event.

eventEmitter.prependOnceListener() It will add the one-time listener to the beginning of the array.

eventEmitter.prependListener() It will add the listener to the beginning of the array.

ITL501 - IP Lab 69
Example 1: Code for creating a program of a simple event:
main.js

const EventEmitter = require('events');


// Initializing event emitter instances
var eventEmitter = new EventEmitter();

// Create an event handler:


var EventHandler = function () {
console.log('Learn nodejs!');
}

// Assign the event handler to an event:


eventEmitter.on('event1', EventHandler);

// Fire the 'scream' event:


eventEmitter.emit('event1');

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');

// Initializing event emitter instances


var eventEmitter = new EventEmitter();

// 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}`);
});

// Declaring listener fun1 to myEvent1


var fun1 = (msg) => {
console.log("Message from fun1: " + msg);
};

// Declaring listener fun2 to myEvent2


var fun2 = (msg) => {

ITL501 - IP Lab 70
console.log("Message from fun2: " + msg);
};

// Listening to myEvent with fun1 and fun2


eventEmitter.on('myEvent', fun1);
eventEmitter.on('myEvent', fun2);

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

Q2. In which language is Node.js written?


a) JavaScript b) C c) C++ d) CoffeeScript e) All 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

Q4. What is Callback?


a) The callback is a technique in which a method calls back the caller method.
b) The callback is an asynchronous equivalent for a function.
c) Both of the above. 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

Q6. The Node.js modules can be exposed using:


a) expose b) module c) exports d) All of the above

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.

Q8. Node.js uses an event-driven, non-blocking I/O model. Is it true?


a) True b)False

Q9. What is an EventEmmitter class?

Q10. Which command is used to see the result?

ITL501 - IP Lab 72
Experiment No.12
Express app

Aim: Creating express app.


Objective:
Express is the most popular minimalistic framework. It is built upon the built-in module HTTP of
NodeJS to facilitate the simple and easy interaction between frontend and backend logic through
API, and also it enables us to organize our business logic in so much pretty manner. It is much
flexible and we can use it for both the web and android. Also, it provides a very simple error
handling procedure.
Approach: Below is the fundamental steps to write an express app. Here we are covering the topics
like setting up the environment with the installation of modules, creating an application, running the
web server, and performing basic communication with the server. Must-Know how to use the node
package manager for basic works, basic knowledge of the terminal for installing dependencies and
modules, basic knowledge of how a web application works, and a good knowledge of ES6.
Step by step Implementation:
Step 1: Write this command in your terminal, to create a nodejs application, because our express
server will work inside the node application.
Syntax:
npm init
This will ask you for few configurations about your project you can fill them accordingly, also you
can change it later from the package.json file.
Note: Use `npm init -y` for default initialization

ITL501 - IP Lab 73
Step 2: Install necessary dependencies for our application.
npm install express
Something like this will be shown on successful installation,

Step 3: The project structure will look like following.

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

const express = require('express');

const app = express();


const PORT = 3000;

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running,
and App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);

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

const express = require('express');


const app = express();
const PORT = 3000;
app.get('/', (req, res)=>{
res.status(200);
res.send("Welcome to root URL of Server");
});

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running,
and App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);

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

const express = require('express');

const app = express();


const PORT = 3000;

app.get('/hello', (req, res)=>{


res.set('Content-Type', 'text/html');
res.status(200).send("<h1>Hello GFG Learner!</h1>");
});

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running, and App is
listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);

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

const express = require('express');

const app = express();


const PORT = 3000;

app.use(express.json());
app.post('/', (req, res)=>{
const {name} = req.body;

res.send(`Welcome ${name}`);
})

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running, and
App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);

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:

Step 5: Sending Files from Server


Step 6: Now we will see how to send files from the server.
Several times we need to transfer the resources from the server as per user request, there are majorly
two methods to send files one is sending static files using middleware and the other one is sending a
single file on a route.
This is our folder structure and we want to serve the files from the Static Files directory as static
files, and the image.jpg on a separate route.

Example 1: Serving entire directory using middleware


Express provides us a middleware express.static(), it accepts two arguments first one is the absolute
root path of the directory whose files we are going to serve.
We can simply use it to serve static files, by providing to app.use().
Syntax:
app.use(path, express.static(root, [options]));
First of all, we are importing an inbuilt module `path`, because later we are going to use one of the
functions provided by this module.
We are simply mounting a middleware at the ‘/static’ route.
The static() middleware requires an absolute path so we use the path module’s join method.
The join() method takes two parameters and joins them as a path, in NodeJS we have a global
attribute __dirname which contains the path of the directory in which the current file exists.
We are providing that joined path to middleware so that it can start serving the files inside that
directory on the given path.
app.js

const express = require('express');


const app = express();
const PORT = 3000;

ITL501 - IP Lab 78
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'Static Files')))

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running,
and App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);

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:

Example 2: Sending a single file on a route with the sendFile() function.


This function accepts an absolute URL of the file and whenever the route path is being accessed the
server provides the file as an HTTP response. This process can be thought of as a single endpoint of
the express.static(). It can be useful when we have to do some kind of processing before sending the
file.
Syntax:
res.sendFile(fileUrl)
We are creating a get request route on the ‘/file’ path
After then we are creating the absolute path by joining the path of current __dirname and the name of
the file we want to send and then passing it to sendFile().
Then route sends the image.jpg file to the user as an HTTP response.
app.js

const express = require('express');


const path = require('path');

const app = express();


const PORT = 3000;

app.get('/file', (req, res)=>{

ITL501 - IP Lab 79
res.sendFile(path.join(__dirname,'image.jpg'));
});

app.listen(PORT, (error) =>{


if(!error)
console.log("Server is Successfully Running, and App is listening on port "+ PORT)
else
console.log("Error occurred, server can't start", error);
}
);

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.

Q3. In which of the following year was Express.js initially released?


a) November 2010 b) November 2011 c) December 2010 d) December 2011

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()

Q5. Which of the following is a middleware in Express.js?


a) function(req){ } b) method(req){ } c) function(req,res,next){ } d) method(req,res,next){ }

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.

Q8. What is the meaning of templating in Express.js?


a) Pug b) EJS c) Mustache d) All 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

You might also like