100% found this document useful (1 vote)
93 views112 pages

IP Final Assginment-15

Uploaded by

Dev Khatanhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
93 views112 pages

IP Final Assginment-15

Uploaded by

Dev Khatanhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

LAB ASSGINMENT 1

Aim: Develop a web application by using HTML Tags , Elements , Attributes , Head , Body ,
Hyperlinks , Formatting Images , Tables , Lists, Frames ,Forms and Multimedia elements
should be used.
Theory :
HTML TAGS:
1: <!DOCTYPE> :- Is the first tag in HTML document which specifies DTD used by the document. l A
DTD is separate file containing formal definition of grammar used in markup language. l The browser
checks the code of document against the rule in declaration. l Tells the browser about the version of
language. l Does not have a closing tag The declaration helps the browser to display a web page
correctly.

2: <html>: Represents and defines the HTML Document.


3: <base>: Defines the base URL that dictates the relative URLs for the document.
4: <head>: contains all the metadata of the HTML document.
5: <link>: Describes the relationship between the document and external resources such
as CSS file, favicons or SVGs.
6: <meta>: Represents the metadata of the HTML document that other elements can’t
describe

7:<style>: Contains style information for a document or part of a document. It


contains CSS, which is applied to the contents of the document containing this
element.
8: <title>: Defines the document's title that is shown in a browser's title bar or a page's tab. It
only contains text; tags within the element are ignored.

9: <body>: represents the content of an HTML document. There can be only one such
element in a document.

10:<footer>: Represents a footer for its nearest ancestor sectioning content or sectioning
root element. A <footer> typically contains information about the author of the section,
copyright data, or links to related documents.

11:<header>: Represents introductory content, typically a group of introductory or


navigational aids. It may contain some heading elements but also a logo, a search form, an
author name, and other elements.
12:<h1>, <h2>, <h3> ,<h4>, <h5> ,<h6>: Represent six levels of section
headings. <h1> is the highest section level and <h6> is the lowest.

13: <nav>: Represents a section of a page whose purpose is to provide navigation


links, either within the current document or to other documents. Common
examples of navigation sections are menus, tables of contents, and indexes.

14: <section>: Represents a generic standalone section of a document, which


doesn't have a more specific semantic element to represent it. Sections should
always have a heading, with very few exceptions.
TEXT CONTENT:

1: <dd>: Provides the description, definition, or value for the preceding term (<dd>)
in a description list (<dl>).

2: <div>: The generic container for flow content. It has no effect on the content or
layout until styled in some way using CSS (e.g., styling is directly applied to it, or
some kind of layout model like flexbox is applied to its parent element).
3: <dl>: Represents a description list. The element encloses a list of groups of
terms (specified using the <dt> element) and descriptions (provided
by <dd> elements). Common uses for this element are to implement a glossary or
to display metadata (a list of key-value pairs).
4:<dt>: Specifies a term in a description or definition list, and as such must be
used inside a <dl> element. It is usually followed by a <dd> element; however,
multiple <dt> elements in a row indicate several terms that are all defined by the
immediate next <dd> element.

5:<hr>: Represents a thematic break between paragraph-level elements: for


example, a change of scene in a story, or a shift of topic within a section.

6:<li>: Represents an item in a list. It must be contained in a parent element: an


ordered list (<ol>), an unordered list (<ul>), or a menu (<menu>). In menus and
unordered lists, list items are usually displayed using bullet points. In ordered lists,
they are usually displayed with an ascending counter on the left, such as a number
or letter.

7: <ol>: Represents an ordered list of items — typically rendered as a numbered


list.
8: <p>: Represents a paragraph. Paragraphs are usually represented in visual
media as blocks of text separated from adjacent blocks by blank lines and/or first-
line indentation, but HTML paragraphs can be any structural grouping of related
content, such as images or form fields.

9:<ul>: Represents an unordered list of items, typically rendered as a bulleted list.

INLINE TEXT SEMANTICS

1: <a>:

Together with its href attribute, creates a hyperlink to web pages, files, email
addresses, locations within the current page, or anything else a URL can address.

2: <br>: Produces a line break in text (carriage-return). It is useful for writing a


poem or an address, where the division of lines is significant.

3: <i>: Represents a range of text that is set off from the normal text for some
reason, such as idiomatic text, technical terms, and taxonomical designations,
among others. Historically, these have been presented using italicized type, which
is the original source of the <i> naming of this element.
IMAGES AND MULTIMEDIA:

1: <audio>: Used to embed sound content in documents. It may contain one or


more audio sources, represented using the src attribute or the source element: the
browser will choose the most suitable one. It can also be the destination for
streamed media, using a Media Stream.
2: <img>: Embeds an image into the document.

3:< video>: Embeds a media player which supports video playback into the
document. You can also use <video> for audio content, but the audio element may
provide a more appropriate user experience.

Table Content:

1: <caption>: Specifies the caption (or title) of a table.


2:<table>: Represents tabular data — that is, information presented in a two-
dimensional table comprised of rows and columns of cells containing data.
3:<td>: Defines a cell of a table that contains data. It participates in the table
model.

4:<th>: Defines a cell as a header of a group of table cells. The exact nature of
this group is defined by the scope and headers attributes.
5:<tr>: Defines a row of cells in a table. The row's cells can then be established
using a mix of <td> Data cell) and <th> (header cell) elements.

FORMS:

1: <button: An interactive element activated by a user with a mouse, keyboard,


finger, voice command, or other assistive technology. Once activated, it performs
an action, such as submitting a form or opening a dialog

2:<fieldset>: Used to group several controls as well as labels (<label>) within a


web form.

3:<form>: Represents a document section containing interactive controls for


submitting information.
4:<input>: Used to create interactive controls for web-based forms to accept data
from the user; a wide variety of types of input data and control widgets are
available, depending on the device and user agent. The <input> element is one of
the most powerful and complex in all of HTML due to the sheer number of
combinations of input types and attributes.
5:<label>: Represents a caption for an item in a user interface.
6:<option>: Used to define an item contained in a select, an <optgroup>, or a
<datalist> element. As such, <option> can represent menu items in popups and
other lists of items in an HTML document.
Lab OutCome:
LO1 : -Identify and apply the appropriate HTML tags and develop a webpage.

CONCLUSION:
We have created a working website using basic HTML tags, 0Attributes , Head , Body ,
Hyperlinks , Formatting Images , Tables , Lists, Frames ,Forms and Multimedia elements
1: index.html

2: second.html
3:third.html

4:fourth.html
5:fivth.html
OUTPUT:
Aim: Using CSS and CSS3 enhance the web application developed in Assignment #1 Color,
Background, Font, Table, List, CSS3 selectors, Pseudo classes, and Pseudo elements properties
should be used to enhance the web pages.
Theory:

CSS stands for "Cascading Style Sheets." It is a style sheet language used to describe the
presentation and formatting of a document written in markup languages like HTML and XML.
CSS allows web developers to control the layout, colors, fonts, and other visual aspects of a web
page, separating the content from its presentation. The primary purpose of CSS is to provide a way
to style web pages consistently across different devices and browsers. Instead of applying styles
directly to individual HTML elements, CSS allows developers to create style rules that can be
applied to multiple elements at once. This approach promotes a more efficient and maintainable
way of managing the appearance of a website. The "Cascading" part of CSS refers to the way
styles are applied in a specific order. If multiple CSS rules target the same element, the browser
follows a set of rules to determine which style should be applied. This includes considering the
specificity of the selector, the order of appearance in the CSS file, and the use of inline styles or
external stylesheets.

1. Color in CSS:

Color is an essential aspect of web design, and CSS provides various ways to define colors for
elements. Colors can be specified using color names, hexadecimal values (#RRGGBB), RGB
values (rgb(R, G, B)), or HSL values (hsl(H, S%, L%)). CSS allows you to set the color of text,
backgrounds, borders, and other elements, enhancing the visual appeal and readability of a web
page.

2. Background in CSS:

CSS allows you to control the background of elements. You can set background colors,
background images, and control their position and behavior using properties like `background-
color`, `background-image`, `background-position`, `background-repeat`, etc. Backgrounds help
improve the overall look and feel of a web page.

3. Font in CSS:
CSS enables you to customize the font used for text on a web page. You can set the font family,
font size, font weight, font style, and more. By choosing appropriate fonts, you can enhance
readability and create a consistent visual identity for your website.

4. Tables in CSS:

CSS allows you to style HTML tables, making them visually appealing and easier to read. You
can apply styles to the table, table headers (`<th>`), table cells (`<td>`), and control borders,
padding, spacing, background colors, etc.

5. Lists in CSS:

CSS provides options to style HTML lists (ordered and unordered). You can remove default list
styles, change bullet styles, control spacing, and add custom styling to list items.

6. CSS3 Selectors:

CSS3 introduced advanced selectors that allow you to target elements based on more complex
criteria. Examples include attribute selectors (`[attribute=value]`), child selectors (`parent >
child`), sibling selectors (`prev + next`), and more. CSS3 selectors give you greater control and
flexibility in styling specific elements on a web page.

7. Pseudo-classes:

Pseudo-classes are used to define styles for elements in specific states or conditions that cannot
be represented with regular selectors. For example, `:hover` targets an element when the user
hovers over it, `:active` targets an element when it is being clicked, and `:first-child` targets the
first child element of its parent.

8. Pseudo-elements:
Pseudo-elements allow you to style parts of an element's content or add content before or after
an element. Commonly used pseudo-elements are `::before` and `::after`, which add content before
and after an element, respectively.

By leveraging these CSS concepts, web developers can create visually appealing and user-friendly
web pages, improving the overall user experience and design of the website.

Conclusion: In conclusion, using CSS (Cascading Style Sheets) is crucial for modern web
development due to the following reasons:

Separation of Concerns: CSS allows the separation of the presentation layer from the HTML
structure, enabling cleaner and more maintainable code. This separation makes it easier to update
the visual style without affecting the content and structure of the web page.

Consistency and Branding: CSS provides the ability to define consistent styles across a website,
ensuring a unified look and feel. By setting fonts, colors, and layouts consistently, you can
establish a strong brand identity and enhance user recognition.

Responsive Web Design: CSS enables responsive web design, allowing websites to adapt and
display correctly on various devices and screen sizes. Media queries and flexible layouts ensure
that the content is accessible and user-friendly on desktops, tablets, and smartphones.

Enhanced User Experience: Properly styled websites created with CSS provide a more pleasant
and engaging user experience. By improving readability, using appealing colors and
backgrounds, and organizing content effectively, users are more likely to stay on the site and find
what they need.

Efficient Styling and Maintenance: CSS allows you to apply styles to multiple elements
simultaneously, reducing redundancy and making maintenance easier. You can define classes
and IDs to target specific elements and update styles globally with minimal effort.

Optimization and Performance: CSS is lightweight and loads quickly, contributing to improved
website performance. By reducing the need for inline styles and leveraging external stylesheets,
you can optimize the loading speed of your web pages.

Flexibility and Customization: With CSS, you have immense flexibility to customize the
appearance of your website. You can use CSS3 properties, pseudo-classes, and pseudo-elements
to create intricate designs, animations, and interactive effects.
1:index.html: Internal Style sheet
<!DOCTYPE html>
<html>
<head>
<title>Internal CSS Form</title>
<style>
.my-form {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}

.my-form label {
display: block;
margin-bottom: 5px;
}

.my-form input[type="text"],
.my-form input[type="email"],
.my-form textarea {
width: 100%;
padding: 5px;
margin-bottom: 10px;
}

.my-form input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<form class="my-form">
<label for="name">Name:</label>
<input type="text" id="name" name="name">

<label for="lastname">Enter your Last name : </label>


<input type="text" id="lastname" name="lname" value="predefined text"/>

<label for="email">Email:</label>
<input type="email" id="email" name="email">

<label for="password">Password:</label>
<input type="password" id="password" name="password" />
<div>
<input type="radio" name="radioelement" id="option1" value="M" />
<label for="option1">Male</label>
<input type="radio" name="radioelement" id="option2" value="F" />
<label for="option2">Female</label>
</div>

<div>
<input type="checkbox" id="cb1" name="cb1" value="1" />
<label for="cb1">Checkbox 1</label>

<input type="checkbox" id="cb2" name="cb2" value="2" />


<label for="cb2">Checkbox 2</label>

<input type="checkbox" id="cb3" name="cb3" value="3" />


<label for="cb3">Checkbox 3</label>
</div>

<br />

<!-- date element -->


<div>
<input type="date" id="date" name="date" />
<label for="date">Date</label>
</div>

<br />

<!-- dropdown element -->


<div>
<label for="options">Choose option : </label>
<select name="optionselected" id="options">
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option 3</option>
</select>
</div>

<br />

<!-- colour element -->


<div>
<label for="colour">Choose a colour:</label>
<input type="color" name="color" id="color" />
</div>

<br />

<!-- file element -->


<div>
<label for="File">Choose a File :</label>
<input type="file" name="file" id="file" />
</div>

<br />
<!-- range element -->
<div>
<label for="Range">Select a range :</label>
<input type="range" name="range" id="range" />
</div>

<br />
<!-- number element -->
<div>
<label for="Number">Choose a number :</label>
<input type="number" name="number" id="number" />
</div>

<label for="message">Message:</label>
<textarea id="message" name="message" rows="4"></textarea>

<a href="second.html"><input type="submit"></a>


</form>
</body>
</html>

1:second.html: External Style sheet


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External STYLE SHEET</title>
<link rel="stylesheet" href="index.html">
<!-- External Style sheet -->
<link rel="stylesheet" href="style.css" />
</head>
<body>

<nav class="navbar">
<ul>
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Contact</a></li>
<li><a href="">Blog</a></li>
<li><a href="">Design</a></li>
</ul>
</nav>
<!-- main section -->

<h1 >The Editors Picked</h1>

<div class="main">
<!-- main title -->
<div class="left">
<!-- left side div -->
<h3>The 28 best skincare products of 2021</h3>

<p class="anc">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Animi,
temporibus? Lorem ipsum dolor sit amet consectetur adipisicing elit.
Perferendis, adipisci inventore nemo neque architecto quis minima
quidem eligendi sint minus officiis dolorum soluta. Corporis ea
praesentium pariatur iusto ratione laborum!
</p>
<br />
<p class="anc">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Aut
excepturi saepe dicta, eius placeat repellendus nihil suscipit
reiciendis deserunt quisquam.
</p>
<br />
<p class="anc">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore
soluta corrupti et, architecto quis corporis accusamus consectetur,
nesciunt dolorum quae voluptates cupiditate nulla. Similique,
deserunt! Architecto, officia est, eveniet totam voluptatem, veniam
aliquid culpa expedita nihil nulla recusandae nam aliquam.
</p>
<!-- left side ends -->
</div><div class="right">
<!-- right side div image part -->
<img src="Images/premium_photo-1690297971162-5fe7ddf2c48d.avif" alt="Heelo" />
</div>
<!-- right side ends -->
</div>
<!-- main title ends -->
<!-- main section ends -->

<div>
NOW Let's learn Inline style sheet
<a href="third.html">Click here</a>
</div>
</body>
</html>
Style.css
h4 {
color: blueviolet ;
background-color: blanchedalmond;
}
/* class has to start with . */
/* but p hum sida element selector se kiya */
/* class selector */
.text-warning{
color: rgb(255, 94, 0);
}

/* id selector */

#foo {
font-size: 40px;
background-color: turquoise;
color: black;
}
.ext{
background-color: black;
color: aqua;
}
/* Priority wise 1:inline
2:internal
3:external */
/* reset style */
* {
margin: 0;
padding: 0;
font-family: 'Teko', sans-serif;
}
/* reset style ends */

body{
background-color: #819fbb;
/* height: 180px; */

.anc{
line-height: 20px;
}

/* nav bar section starts */


/* bringing li items in one line */
.navbar li {
display: inline-block;
padding: 20px;
/* background-color:orange; */
}
.navbar{
padding: 20px 20px;
/* top-bottom=20px */
/* left-right=20px */
background-color: #003049;
opacity: 0.5;
position: sticky;
top: 0;
}

/* removing underline and changing colour */


.navbar a {
text-decoration: none;
color: #ffff;
/* padding: 20px; */

}
/* nav bar section ends */
.left ,.right{
display: inline-block;
width: 50%;
vertical-align: top;
}
img{
width: 100%;
border-radius: 10px;
height: calc(100vh - 100px);
position: relative;
bottom: 50px;

.main{
margin: 15px 50px;
background-color: #f5ebd3;
padding: 30px;
border-radius: 5px;
/* height: calc(100vh - 100px); */
}

h1{
margin: 10px;
padding-left: 30px;
}
3:third.html
<!DOCTYPE html>
<html>
<head>
<title>Inline CSS Form</title>
</head>
<body>
<form style="max-width: 400px; margin: 0 auto; padding: 20px; border: 1px solid #ccc;
border-radius: 5px; background-color: aqua;">
<label for="name">Name:</label>
<input type="text" id="name" name="name" style="width: 100%; padding: 5px; margin-
bottom: 10px;">

<label for="email">Email:</label>
<input type="email" id="email" name="email" style="width: 100%; padding: 5px;
margin-bottom: 10px;">

<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" style="width: 100%; padding: 5px;
margin-bottom: 10px;"></textarea>

<input type="submit" value="Submit" style="background-color: #4CAF50; color: white;


padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">
</form>
</body>
</html>

OUTPUT:
Index.html
Second.html
Third.html
LAB ASSIGNMENT -03
AIM: Create a Website Using BootStrap.
Theory:

Bootstrap is a powerful, feature-packed frontend toolkit. Build anything—from


prototype to production—in minutes.
Include Bootstrap’s CSS and JS. Place the <link> tag in the <head> for our CSS, and
the <script> tag for our JavaScript bundle (including Popper for positioning
dropdowns, poppers, and tooltips) before the closing </body>.
Grid: Bootstrap’s grid system uses a series of containers, rows, and columns to layout and align
content. It’s built with flexbox and is fully responsive. Below is an example and an in-depth
explanation for how the grid system comes together. Our grid supports Six responsive
breakpoints . Breakpoints are based on min-width media queries, meaning they affect that
breakpoint and all those above it (e.g., .col-sm-4 applies to sm, md, lg, xl, and xxl). This means
you can control container and column sizing and behavior by each breakpoint.

• Containers center and horizontally pad your content. Use .container for a responsive
pixel width, .container-fluid for width: 100% across all viewports and devices, or a
responsive container (e.g., .container-md) for a combination of fluid and pixel widths.
• Rows are wrappers for columns. Each column has horizontal padding (called a gutter)
for controlling the space between them. This padding is then counteracted on the rows
with negative margins to ensure the content in your columns is visually aligned down the
left side. Rows also support modifier classes to uniformly apply column sizing and gutter
classes to change the spacing of your content.
• Columns are incredibly flexible. There are 12 template columns available per row,
allowing you to create different combinations of elements that span any number of
columns. Column classes indicate the number of template columns to span (e.g., col-
4 spans four). widths are set in percentages so you always have the same relative sizing
• Grid System: Bootstrap's grid system allows developers to create responsive layouts by dividing
the screen into a 12-column grid. This makes it easy to arrange content in different configurations
based on screen size.

Navbar:

Navbars require a wrapping .navbar with .navbar-expand{-sm|-md|-lg|-xl|-


xxl} for responsive collapsing and color scheme classes.

• Navbars and their contents are fluid by default. Change the container to
limit their horizontal width in different ways.
• Use our spacing and flex utility classes for controlling spacing and
alignment within navbars.
• Navbars are responsive by default, but you can easily modify them to
change that. Responsive behavior depends on our Collapse JavaScript
plugin.
• Ensure accessibility by using a <nav> element or, if using a more generic
element such as a <div>, add a role="navigation" to every navbar to explicitly
identify it as a landmark region for users of assistive technologies.
• Indicate the current item by using aria-current="page" for the current page
or aria-current="true" for the current item in a set.

Navbars come with built-in support for a handful of sub-components. Choose


from the following as needed:

• .navbar-brand for your company, product, or project name.


• .navbar-nav for a full-height and lightweight navigation (including support
for dropdowns).
• .navbar-toggler for use with our collapse plugin and other navigation
toggling behaviors.
• Flex and spacing utilities for any form controls and actions.
• .navbar-text for adding vertically centered strings of text.
• .collapse.navbar-collapse for grouping and hiding navbar contents by a
parent breakpoint.

The Bootstrap navigation bar component allows developers to create responsive and
customizable navigation menus, complete with dropdowns, branding, and mobile
responsiveness.

Forms:

Bootstrap’s form controls expand on our Rebooted form styles with classes. Use these
classes to opt into their customized displays for a more consistent rendering across
browsers and devices.
Be sure to use an appropriate type attribute on all inputs (e.g., email for email address
or number for numerical information) to take advantage of newer input controls like
email verification, number selection, and more.
Bootstrap offers pre-styled form elements like input fields, checkboxes, radio buttons,
dropdowns, and more, making it easier to create aesthetically pleasing and consistent
forms.
Typography: Bootstrap offers a set of typography styles, including headings, paragraphs,
lists, and more, with consistent and visually pleasing typography across different devices.

Buttons: Bootstrap provides styles for creating various types of buttons, such as primary,
secondary, success, danger, and more, along with different sizes and styles..
Cards: Cards are versatile content containers that can hold various types of content, such
as text, images, and buttons. They're often used to display blocks of content in an
organized manner.
Alerts: Bootstrap provides styled alerts for conveying different types of messages or
notifications to users.
Modal Dialogs: Modal dialogs are pop-up windows that overlay the main content and are
used for displaying additional information or actions without navigating away from the
current page.
Carousel: Bootstrap's carousel component enables the creation of image sliders and
carousels for showcasing multiple images or pieces of content.
Icons: Bootstrap includes an icon library (formerly Glyphicons) that provides a set of
scalable vector icons that can be easily integrated into your design.
Utilities: Bootstrap also offers a variety of utility classes that help with spacing,
alignment, display properties, and more.

LAB OUTCOME:
LO3: Construct a responsive website using Bootstrap.
CONCLUSION:
Bootstrap stands as a foundational cornerstone in contemporary web development, offering a
comprehensive toolkit of pre-designed elements that empower developers to create responsive, visually
appealing, and user-friendly websites and applications. Through its versatile grid system, extensive
typography options, pre-styled components, and customizable features, Bootstrap streamlines the
development process while ensuring consistency and responsiveness across various devices and screen
sizes. Its robust framework not only accelerates the creation of sophisticated interfaces but also
encourages best practices in design and layout.0.
1:index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Website using pure bootstrap</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-
9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM"
crossorigin="anonymous"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
integrity="sha512-
iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==
"
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
</head>
<body>

<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-
geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz"
crossorigin="anonymous"
defer
></script>

<!-- navbar section starts -->


<!-- <section class="bg-secondary">
<nav>
<ul style="text-decoration: none;">
<li><a href="">Home</a></li>
<li><a href="">Skills</a></li>
<li><a href="">About</a></li>
<li><a href="">Project</a></li>
<li><a href="">Contact-us</a></li>
</ul>
</nav>
</section> -->

<nav class="navbar navbar-expand-lg bg-dark m-0">


<a class="navbar-brand" href="#"><i class="fa-solid fa-person text-warning fa-
2x"></i></a>

<button class="navbar-toggler bg-white collapsed " type="button" data-bs-


toggle="collapse" data-bs-target="#ournavbar" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>

<div class="collapse navbar-collapse justify-content-between"


id="ournavbar">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">

<!-- <li class="nav-item">


<a class="nav-link"><i class="fa-solid fa-person text-
warning"></i></a>

</li> -->
<li class="nav-item">
<a class="nav-link active mx-3 text-uppercase" aria-current="page"
href="#hero" style="color: white; ">Home</a>
</li>
<li class="nav-item">
<a class="nav-link mx-3 text-uppercase" href="#skills" style="color:
white;">Skills</a>
</li>

<li class="nav-item dropdown">


<a class="nav-link dropdown-toggle mx-3 text-
uppercase" href="#project" role="button" data-bs-toggle="dropdown" aria-
expanded="false" style="color: white;">
Projects
</a>
<ul class="dropdown-menu " style="width: 200px;">
<li><a class="dropdown-item" href="#project">Project-1</a></li>
<li><a class="dropdown-item" href="#project">Project-2</a></li>
<li><a class="dropdown-item" href="#project">Project-3</a></li>
<li><a class="dropdown-item" href="#project">Final-
project</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link mx-3 text-uppercase" href="#about" style="color:
white;">About</a>
</li>
<li class="nav-item">
<a class="nav-link mx-3 text-uppercase" href="#contact"
style="color: white;">Contact</a>
</li>
</ul>
<form>
<div class="input-group">
<input class="form-control" type="search" placeholder="Search here..."
aria-label="Search" >
<span class="input-group-text"><button type="submit" class="btn"><i
class="fa-solid fa-magnifying-glass text-secondary"></i></button></span>

</div>
</form>
</div>
</nav>
<!-- navbar section ends -->

<!-- hero section starts -->

<section id="hero">
<div class="container-fluid ">
<div
class="row align-items-center justify-content-center bg-info"
style="height: 100vh"
>
<div class="col-md-10 text-center">
<p class="display-3">
<span class="text-warning text-capitalize">pure bootstrap</span>
<span class="text-white fw-bold">Website</span>
</p>

<p class="lead fst-italic">


Lorem ipsum dolor, sit amet consectetur adipisicing elit.
</p>

<div class="btn btn-warning mx-3">Click-here</div>


<div class="btn btn-danger mx-3 text-white">Click-here</div>

<!-- <a href="" class="btn btn-warning">Click-here</a> -->


</div>
</div>
</div>
</section>
<!-- hero section ends -->

<!-- skills section starts -->

<section class="bg-light container-fluid" id="skills">


<div class=" row justify-content-center text-center mb-3 py-2 fw-bold ">
<div class="col">
<div>
<p class="display-3 text-warning text-capitalize">skills</p>
<p class="lead">
Lorem ipsum dolor sit, amet consectetur adipisicing.
</p>

<!-- <span class="display-3 text-warning text-capitalize">Skills</span>


<span class="lead">Lorem ipsum dolor sit, amet consectetur
adipisicing elit. Assumenda, praesentium.</span> -->
</div>
</div>
</div>

<div class="row text-center justify-content-center">


<div class="col-lg-4 col-md-10 col-10">
<i class="fa-solid fa-laptop text-warning fa-6x"></i>
<h1 class="text-secondary">Development</h1>
<p class="text-muted text-center">
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Voluptates, reprehenderit.

</p>
<p class="btn btn-outline-warning">Learn more</p>
<!-- <a class="btn btn-outline-warning"></a>remove href href="" while using a
as button -->
</div>
<div class="col-lg-4 col-md-10 col-10">
<i class="fa-solid fa-pen-to-square fa-6x text-warning"></i>
<h1 class="text-secondary">Design</h1>
<p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing
elit. Omnis, mollitia.</p>
<p class="btn btn-outline-warning">Learn more</p>

</div>
<div class="col-lg-4 col-md-10 col-10">
<i class="fa-solid fa-gears fa-6x text-warning"></i>
<h1 class="text-secondary">Creativity</h1>
<p class="text-muted">Lorem ipsum dolor sit amet consectetur adipisicing elit.
Suscipit, nisi.</p>
<p class="btn btn-outline-warning">Learn more</p>

</div>

</div>
</section>
<!-- skills section ends -->

<!-- project section starts -->


<section class="container-fluid">

<div class="row justify-content-center text-center py-2 m-0" >


<div class="col"id="project">
<div>
<p class="display-3 text-warning text-capitalize">Projects</p>
<p class="lead">
Lorem ipsum dolor sit, amet .
</p>
</div>
</div>
</div>

<div class="row justify-content-center text-center ">


<div class="col-lg col-md-6 p-3" id="pro-1">
<img src="https://plus.unsplash.com/premium_photo-1661775434014-
9c0e8d71de03?ixlib=rb-
4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8MXx8b2ZmaWNlfGVufDB8fDB8fHww&auto=format&fit=crop&w=5
00&q=60" alt="" class="img-thumbnail ">
<h2 class="fw-bold text-warning">Project 1</h2>
<p class="text-muted">Lorem ipsum dolor, sit amet consectetur adipisicing
elit. Qui, neque?</p>
</div>

<!-- class=img-fluid -->

<div class="col-lg col-md-6 p-3" >


<img src="https://plus.unsplash.com/premium_photo-1661775434014-
9c0e8d71de03?ixlib=rb-
4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8MXx8b2ZmaWNlfGVufDB8fDB8fHww&auto=format&fit=crop&w=5
00&q=60" alt="" class="img-thumbnail">
<h2 class="fw-bold text-warning mt-1">Project 2</h2>
<p class="text-muted">Lorem ipsum dolor, sit amet consectetur adipisicing
elit. Qui, neque?</p>
</div>

<div class="col-lg col-md-6 p-3">


<img src="https://plus.unsplash.com/premium_photo-1661775434014-
9c0e8d71de03?ixlib=rb-
4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8MXx8b2ZmaWNlfGVufDB8fDB8fHww&auto=format&fit=crop&w=5
00&q=60" alt="" class="img-thumbnail">
<h2 class="fw-bold text-warning mt-1">Project 3</h2>
<p class="text-muted">Lorem ipsum dolor, sit amet consectetur adipisicing
elit. Qui, neque?</p>
</div>

<div class="col-lg col-md-6 p-3">


<img src="https://plus.unsplash.com/premium_photo-1661775434014-
9c0e8d71de03?ixlib=rb-
4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8MXx8b2ZmaWNlfGVufDB8fDB8fHww&auto=format&fit=crop&w=5
00&q=60" alt="" class="img-thumbnail">
<h2 class="fw-bold text-warning mt-1">Project 4</h2>
<p class="text-muted">Lorem ipsum dolor, sit amet consectetur adipisicing
elit. Qui, neque?</p>
</div>

</div>
</section>
<!-- project section ends -->

<!-- Team section starts -->

<section class="bg-secondary container-fluid " id="about">

<div class="row text-center py-2 container-fluid fw-bold">


<div class="col">
<div>
<p class="display-3 text-warning text-capitalize">Teams</p>
<p class="lead">
Lorem ipsum dolor sit, amet .
</p>
</div>
</div>
</div>

<div class="row text-center py-2 justify-content-center ">


<div class="col-lg col-md-6 col-8 py-2">
<div class="card" >
<img src="https://images.unsplash.com/photo-1529672425113-
d3035c7f4837?ixlib=rb-
4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8M3x8a2lkfGVufDB8fDB8fHww&auto=format&fit=crop&w=500&q
=60" class="card-img-top" alt="...">
<div class="card-body">
<h3 class="card-title text-muted">John Doe</h3>
<p class="card-subtitle">Lorem ipsum dolor sit.</p>
</div>
<div class="card-footer text-end ">
<i class="fa-brands fa-square-youtube fa-3x text-danger mx-2"></i>
<i class="fa-brands fa-square-twitter fa-3x text-info mx-2"></i>
<i class="fa-brands fa-square-facebook fa-3x text-primary mx-2"></i>
</div>
</div>
</div>

<div class="col-lg col-md-6 col-8 py-2">


<div class="card" >
<img src="https://images.unsplash.com/photo-1529672425113-
d3035c7f4837?ixlib=rb-
4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8M3x8a2lkfGVufDB8fDB8fHww&auto=format&fit=crop&w=500&q
=60" class="card-img-top" alt="...">
<div class="card-body">
<h3 class="card-title text-muted">Alex Dae</h3>
<p class="card-subtitle">Lorem ipsum dolor sit.</p>
</div>
<div class="card-footer text-end ">
<i class="fa-brands fa-square-youtube fa-3x text-danger mx-2"></i>
<i class="fa-brands fa-square-twitter fa-3x text-info mx-2"></i>
<i class="fa-brands fa-square-facebook fa-3x text-primary mx-2"></i>
</div>
</div>
</div>

<div class="col-lg col-md-6 col-8 py-2">


<div class="card" >
<img src="https://images.unsplash.com/photo-1529672425113-
d3035c7f4837?ixlib=rb-
4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8M3x8a2lkfGVufDB8fDB8fHww&auto=format&fit=crop&w=500&q
=60" class="card-img-top" alt="...">
<div class="card-body">
<h3 class="card-title text-muted">Jay Sharma</h3>
<p class="card-subtitle">Lorem ipsum dolor sit.</p>
</div>

<div class="card-footer text-end ">


<i class="fa-brands fa-square-youtube fa-3x text-danger mx-2"></i>
<i class="fa-brands fa-square-twitter fa-3x text-info mx-2"></i>
<i class="fa-brands fa-square-facebook fa-3x text-primary mx-2"></i>
</div>
</div>
</div>

<div class="col-lg col-md-6 col-8 py-2">


<div class="card" >
<img src="https://images.unsplash.com/photo-1529672425113-
d3035c7f4837?ixlib=rb-
4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8M3x8a2lkfGVufDB8fDB8fHww&auto=format&fit=crop&w=500&q
=60" class="card-img-top" alt="...">
<div class="card-body">
<h3 class="card-title text-muted">Khushiii</h3>
<p class="card-subtitle">Lorem ipsum dolor sit.</p>
</div>

<div class="card-footer text-end ">


<i class="fa-brands fa-square-youtube fa-3x text-danger mx-2"></i>
<i class="fa-brands fa-square-twitter fa-3x text-info mx-2"></i>
<i class="fa-brands fa-square-facebook fa-3x text-primary mx-2"></i>
</div>
</div>
</div>

</div>
</section>
<!-- Team section ends -->
<!-- progress section starts -->
<section class="container-fluid">
<div class="row text-center py-2 fw-bold ">
<div class="col">
<div>
<p class="display-3 text-warning text-capitalize">Progress</p>
</div>
</div>
</div>

<div class="row justify-content-center py-2">


<div class="col-lg-4 col-md-8">
<h2 class="text-muted">HTML</h2>
<div class="progress bg-secondary" role="progressbar" aria-label="Basic
example" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"b>
<div class="progress-bar bg-warning progress-bar-striped" style="width:
25%">25</div>
</div>
</div>
</div>
</section>
<!-- progress section ends -->

<!-- contact us starts -->


<section class="container-fluid" id="contact">
<div class="row text-center py-2 fw-bold">
<div class="col">
<p class="display-4 text-warning text-capitalize m-1">Contact-us</p>
<p class="lead ">
Lorem ipsum dolor sit, amet .
</p>
</div>
</div>

<div class="row justify-content-center">


<div class="col-lg-4 col-md-8">
<form>
<div class="mb-3">
<label for="Name" class="form-label">Name:</label>
<input type="text" class="form-control" id="Name" placeholder="Enter your
name">
</div>
<div class="mb-3">
<label for="InputEmail1" class="form-label">Email:</label>
<input type="email" class="form-control" id="InputEmail1" aria-
describedby="emailHelp" placeholder="Enter your email">
<!-- <div id="emailHelp" class="form-text">We'll never share your email
with anyone else.</div> -->
</div>
<div class="mb-3">
<label for="Comment" class="form-label" >Comment:</label>
<input type="text" class="form-control" id="Comment" placeholder="Enter
comment" style="height: 80px;">
</div>

<div class="mb-3">
<label for="comment1">Comments:</label>
<textarea class="form-control" placeholder="Leave a comment here"
id="comment1" style="height: 100px"></textarea>

</div>

<div class="text-center">
<button type="submit" class="btn btn-warning w-100">Submit</button>
</div>
</form>

</div>
</div>
</section>
<!-- contact us ends -->

<!-- footer starts -->


<section class="container-fluid bg-secondary mt-2">
<div class="row text-center justify-content-center text-white ">
<div class="col">
<h2 >BOOTSTRAP PROJECT</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusamus,
veritatis?</p>
<i class="fa-brands fa-square-facebook fa-2x text-primary mx-2"></i>
<i class="fa-brands fa-square-twitter fa-2x text-info mx-2"></i>
<i class="fa-brands fa-square-google-plus fa-2x mx-2 text-muted"></i>
<i class="fa-brands fa-square-youtube fa-2x text-danger mx-2"></i>
<p> <i class="fa-regular fa-copyright"></i>Copy-right 2023-Made by
Khushiii</p>
</div>
</section>
<!-- footer ends -->
</body>
</html>

OUTPUT:
LAB ASSIGNMENT -4A
AIM: Implement various Operations such as Conditional , Loops , Functions.
LAB OUTCOME:
LO4: Use JavaScript to perform various Operations.
THEORY:
FUNCTION:
• Functions are the building blocks of readable, maintainable, and reusable code.
• Functions are defined using the function keyword.
• To force execution of the function, it must be called.
• This is called as function invocation
Classification of function:
1. Returning:
• Functions may also return the value along with control, back to the caller.
• Such functions are called as returning functions.
• A returning function must end with a return statement.
• A function can return at the most one value. In other words, there can be only
one return statement per function.
• The return statement should be the last statement in the function
2. Parametrized
• Parameters are a mechanism to pass values to functions.
• Parameters form a part of the function’s signature.
• The parameter values are passed to the function during its invocation.
• Unless explicitly specified, the number of values passed to a function must match
the number of parameters defined
3.Default Function Parameter :
• In ES6, a function allows the parameters to be initialized with default values, if no
values are passed to it or it is undefined.
4 • Rest Parameters:
• Rest parameters are similar to variable arguments in Java.
• Rest parameters doesn’t restrict the number of values that you can pass to a
function.
• To declare a rest parameter, the parameter name is prefixed with three periods,
known as the spread operator.
• A rest parameter allows you to represent an indefinite number of arguments as
an array.
5.Anonymous Function :
• Functions that are not bound to an identifier (function name) are called as
anonymous functions.
• These functions are dynamically declared at runtime.
• Anonymous functions can accept inputs and return outputs, just as standard
functions do.
• An anonymous function is usually not accessible after its initial creation.
• Variables can be assigned an anonymous function.
• Such an expression is called a function expression
6.Lambda Function/ Arrow Function
• refers to anonymous functions in programming.
• Lambda functions are a concise mechanism to represent anonymous functions.
• These functions are also called as Arrow functions.
• There are 3 parts to a Lambda function –
• Parameters − A function may optionally have parameters.
• The fat arrow notation/lambda notation (=>): It is also called as the goes to operator.
• Statements − Represents the function’s instruction set. ([param1, parma2,…param n]
)=>statement;

Loops:
• Certain instructions require repeated execution.
• Loops are an ideal way to do the same.
• A loop represents a set of instructions that must be repeated.
• Definite Loop:
• A loop whose number of iterations are definite/fixed is termed as a definite loop.
• The ‘for loop’ is an implementation of a definite loop
Classification of loop:
1.For Loops:
For loops are commonly used when you know the number of iterations you want to
perform. They consist of three parts: initialization, condition, and increment (or
decrement). For each iteration, the condition is evaluated, and if it's true, the loop body is
executed.
2.While Loops:
While loops are used when you want to repeatedly execute a block of code as long as a
specified condition is true. The condition is checked before each iteration, and if it's true,
the loop body is executed.
3.forof: loop, which is specifically designed for iterating over values in arrays, strings,
maps, sets, and other iterable objects, and the
4.forEach method, which is available on arrays for iterating through their elements.
5.do-while:
The condition is checked after the loop body is executed. This means that the loop body
will always execute at least once, regardless of whether the condition is initially true or
false.
Conditional Statement:
Conditional statements in web development are used to make decisions based on certain
conditions. They allow your code to execute different blocks of code depending on
whether a specified condition is true or false. Conditional statements are essential for
creating dynamic and interactive web applications. The most common types of
conditional statements are:

1.if Statement: The if statement is used to execute a block of code if a specified


condition is true. It's the most basic form of conditional statement.

2. if-else Statement: The if-else statement is used to execute one block of code if a
condition is true and another block of code if the condition is false.
3. if-else if-else Statement: This is an extension of the if-else statement that allows
you to test multiple conditions and execute corresponding blocks of code.
These conditional statements allow you to control the flow of your code based on
different conditions, enabling you to create responsive and interactive web applications.
They are often used in combination with loops, functions, and other programming
constructs to achieve more complex behavior in your web development projects.
CONCULSION:
We have Studied Various operation on Function , Loops and Conditional Statement.
FUNCTIONS:
LOOPS:
CONDITIONAL:
Write a JavaScript code to change the background color of the web page
automatically after every 5 second.
LAB ASSGINMENT – 4B
Aim: Write a program on inheritance, iterators and generators.
Lab Outcome:
LO4- Use JavaScript to develop interactive web Pages.
Theory:
Iterators in JavaScript:
An iterator is an object that allows you to traverse or iterate through a
collection of data, such as an array or an object. In JavaScript, iterators are
typically used with iterable data structures like arrays, strings, and objects.
Iterators provide a standardized way to access elements in a sequence, one at a
time, and they work with the for...of loop and other looping constructs.
Iterators are defined by two methods:
next(): This method returns an object with two properties: value (the current
element in the iteration) and done (a boolean indicating whether the iteration
is complete).
Symbol.iterator: This is a symbol property that should be defined on an
iterable object. It returns an iterator object, which has a next() method.
Example of using an iterator with an array:
const iterable = [1, 2, 3];
const iterator = iterable[Symbol.iterator]();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

Generators in JavaScript:
Generators are a special type of function in JavaScript introduced in ES6. They
allow you to pause and resume the execution of a function, which is useful for
creating iterators, asynchronous operations, and managing complex control
flows. Generators are defined using the function* syntax and contain one or
more yield statements. When a generator function is called, it returns an
iterator called a generator object. You can use the generator object's next()
method to control the execution of the generator function.
Example of a simple generator:
function* myGenerator() { yield 1; yield 2; yield 3; }
const generator = myGenerator();
console.log(generator.next()); // { value: 1, done: false }
console.log(generator.next()); // { value: 2, done: false }
console.log(generator.next()); // { value: 3, done: false }
console.log(generator.next()); // { value: undefined, done: true }
Generators are powerful for handling asynchronous operations, such as
fetching data from a server or working with streams, where you can pause
execution until data is available.

Inheritance in JavaScript:
In JavaScript, inheritance is achieved through prototype-based inheritance.
Objects inherit properties and methods from their prototype objects. You can
create constructor functions or classes and assign methods to their prototypes
to create inheritance relationships.
Example of inheritance using constructor functions and prototypes:
function Animal(name) {
this.name = name;
}
Animal.prototype.sayName = function() {
console.log("My name is " + this.name);
};
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
const myDog = new Dog("Buddy", "Golden Retriever");
myDog.sayName(); // Output: My name is Buddy

JavaScript also supports other forms of inheritance like mixin inheritance,


where you can mix in functionality from one object or module into another,
and ES6 introduced a more class-like syntax for inheritance using the class
keyword. Under the hood, classes in JavaScript still use prototypes for
inheritance.

Conclusion:
Iterators in JavaScript are objects that allow you to traverse through collections
of data one element at a time. They are used with iterable data structures like
arrays and strings, and they provide a standard way to access elements using
the next() method.
Generators are special functions that allow you to pause and resume their
execution. They are defined using the function* syntax and contain yield
statements. Generators are used for creating iterators, handling asynchronous
operations, and managing complex control flows.
Inheritance in JavaScript is primarily achieved through prototype-based
inheritance. Objects inherit properties and methods from their prototype
objects. Constructor functions or classes can be used to create objects with
shared behavior. JavaScript also supports other forms of inheritance like mixin
inheritance, which allows you to mix functionality from one object into
another, and ES6 introduced a class-like syntax for inheritance, although it still
relies on prototypes under the hood
Iterator:

Generator:

Single inheritance example:


Multilevel Inheritance :
Lab Assginment -5a
Aim: Write a Javascript Program to study arrow functions, DOM Manipulation
and CSS Manipulations .
Lab Outcome: LO4- Use JavaScript to develop interactive web Pages.
Theory:
Arrow Functions: Arrow functions were introduced in ECMAScript 6 (ES6) as a
more concise way to write function expressions in JavaScript. Here are some
key points about arrow functions:
Syntax: Arrow functions use a shorter syntax compared to traditional function
expressions, with the => (fat arrow) operator.
Lexical this: Arrow functions do not have their own this binding; they inherit
this from the surrounding code. This behavior can be advantageous in certain
situations, especially when working with callbacks and event handlers.
Example of an arrow function:
const add = (a, b) => a + b;
DOM Manipulation: The Document Object Model (DOM) is a programming
interface provided by web browsers that allows JavaScript to interact with and
manipulate web page content. Key concepts related to DOM manipulation
include:
Selecting Elements: You can use methods like getElementById, querySelector,
and getElementsByClassName to select HTML elements on a web page.
Modifying Elements: You can change the content, attributes, or styles of DOM
elements using properties and methods like innerHTML, setAttribute, and style.
Creating and Appending Elements: You can create new DOM elements using
document.createElement and append them to the DOM tree with methods like
appendChild.
Event Handling: DOM elements can respond to user interactions (e.g., clicks)
by attaching event listeners using methods like addEventListener.
Example of selecting an element and modifying its content:
const element = document.getElementById('myElement');
element.innerHTML = 'New content';
CSS Manipulations: CSS manipulation in JavaScript involves changing the styles
of HTML elements dynamically. Key points related to CSS manipulation include:
Accessing Styles: You can access the styles of an element using its style
property. This property provides access to CSS properties and values.
Modifying Styles: You can change CSS properties and values using JavaScript.
For example, you can set element.style.backgroundColor to change the
background color of an element.
CSS Classes: Manipulating CSS classes is a common way to apply and remove
predefined styles to/from elements. Use element.classList to manage CSS
classes.
Example of modifying CSS styles:
const element = document.getElementById('myElement');
element.style.backgroundColor = 'blue';
Conclusion: Arrow functions provide a concise way to define functions, DOM
manipulation allows you to interact with and modify the structure and content
of web pages, and CSS manipulation enables you to dynamically change the
styles of HTML elements. These concepts are fundamental for building
interactive and responsive web applications
DOM Manipulation

Css manipulation
Arrow Function
ASSIGNMENT – 5B

AIM: Write a Javascript program.


a. Implement the concept of Promise(callback)
b. Fetch (Client Server Communication
c. Asynchronous JavaScript
LAB OUTCOME:
LO4-Use JavaScript to develop interactive web Pages

THEORY:
Promises are important building blocks for asynchronous operations in JavaScript. A Promise
is a special JavaScript object.It produces a value after an asynchronous operation completes
successfully, or an error if it does not complete successfully due to time out, network error, and
so on.Successful call completions are indicated by the resolve function call, and errors are
indicated by the reject function call.They help avoid the so-called "callback hell" and make
asynchronous code easier to write and understand.

A Promise represents a value that might not be available yet, but will be resolved in the future.
It has three possible states:
• Pending: The initial state of a promise when it's created.
• Fulfilled (Resolved): The state when the promise has successfully completed its operation
and resolved to a value.
• Rejected: The state when the promise encountered an error or failed to complete its
operation.

create a promise using the promise constructor: The constructor function takes a function as an
argument. This function is called the executor function.
let promise = new Promise(function(resolve, reject) { // Make an asynchronous call and either
resolve or reject });
The executor function takes two arguments, resolve and reject.These are the callbacks provided
by the JavaScript language.For the promise to be effective, the executor function should call
either of the callback functions, resolve or reject. The new Promise() constructor returns a
promise object.As the executor function needs to handle async operations, the returned promise
object should be capable of informing when the execution has been started, completed
(resolved) or returned with error (rejected).
result – This property can have the following values:
● undefined: Initially when the state value is pending.
● value: When resolve(value) is called.
● error: When reject(error) is called
These internal properties are code-inaccessible but they are inspectable.This means that we will
be able to inspect the state and result property values using the debugger tool, but we will not
be able to access them directly using the program
Using .then() and .catch():
Once the promise is created, you can chain .then() and .catch() methods to handle the resolved
and rejected outcomes respectively.
myPromise
.then((resolvedValue) => {
// Handle successful result
})
.catch((error) => {
// Handle error
});
The .then() method takes a callback function that is executed when the promise is resolved.
The .catch() method handles errors that might occur during the promise's execution.
The .finally() handler performs cleanups like stopping a loader, closing a live connection, and
so on.The finally() method will be called irrespective of whether a promise resolves or rejects.
It passes through the result or error to the next handler which can call a .then() or .catch() again

CONCULSION: In JavaScript, Promises are essential for managing asynchronous tasks,


providing a structured way to handle success and errors. They enhance code readability, support
chaining, and integrate well with async/await, making asynchronous programming more
organized and dependable.
Code:
var dummyPromise='https://some-api.com/posts';
var dummyPromise = new Promise((resolve, reject) => {
const success = true; // or false
if (success) {
resolve("Promise was fulfilled with dummy data!");
} else {
reject("Promise was rejected with dummy error!");
}
});

dummyPromise.then(result => {
console.log(result); // This will be executed if the promise is resolved
}).catch(error => {
console.error(error); // This will be executed if the promise is rejected
});

// Using Promises
function fetchData() {
return new Promise((resolve, reject) => {
fetch('https://api.github.com/')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
resolve(data);
})
.catch(error => {
reject(error);
});
});
}
// Calling the fetchData function
fetchData()
.then(data => {
console.log('Fetched data:', data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Output:
Lab Assginment – 6a
Aim: WAP to implement the concept of props and state.
LAB OUTCOME:
LO5 – Construct front end application using React.

Theory:
In React, props and state are two fundamental concepts used to manage and
pass data within a component and its child components. Understanding the
difference between them is crucial for building React applications.
Props (short for Properties): Props are read-only and are used to pass data
from a parent component to a child component.
They are essentially the way you can customize and configure a component
when you use it in your application.
Props are immutable, meaning that once you pass them to a component, you
cannot change them within that component.
Props help make components reusable and maintainable by allowing you to
provide different data to the same component in different parts of your
application.
Example of using props:
// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const name = 'John';
return (
<div>
<ChildComponent name={name} />
</div>
);
}
// ChildComponent.js
import React from 'react';
function ChildComponent(props) {
return <p>Hello, {props.name}!</p>;
}
export default ChildComponent;
State:
State is used to manage and store data that can be changed or updated within
a component.
Unlike props, state is mutable and can be modified using the setState method
provided by React.
State is primarily used for managing a component's internal data and handling
user interactions or changes over time.
Components can have their own state, which is separate from the props they
receive.
When state changes, React re-renders the component to reflect the updated
data.
Example of using state:
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
incrementCount() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.incrementCount()}>Increment</button>
</div>
);
}
}
export default Counter;

Conclusion: Props are used for passing data into a component, while state is
used for managing and updating data within a component. Props are read-only,
and state is mutable. By using both props and state effectively, you can build
dynamic and interactive React applications.
functional component:

class component:
App.js
ASSIGNMENT – 6B

AIM: WAP to implement the concept of forms and events.


Create a React JS registration Form consisting of textbox, textarea, selection input, check
box, radio button, submit button and reset button handling onSubmit, onClick and keyDown
events.
LAB OUTCOME:
LO5- Construct front end application using React.
THEORY:
Forms in React:
1. Form Elements: In React, you can create forms using standard HTML form elements such
as `<input>`, `<textarea>`, and `<select>`. These elements are used to collect and submit user
data.
2. Controlled Components: React encourages the use of controlled components for forms. A
controlled component is an input element whose value is controlled by the React component's
state. This means you store the input's value in the component's state and update it in
response to user interactions.
3. State Management: React components have a state object that stores data relevant to the
component. To make a form element a controlled component, you link its value attribute to a
corresponding piece of state. When the user interacts with the form, the component's state is
updated, and the UI re-renders to reflect the new state.
Events in React:
1. Event Handling: In React, event handling is similar to handling events in regular
JavaScript. You can use event handlers like `onClick`, `onChange`, `onSubmit`, etc., to
respond to user interactions.
2. Event Binding: When using class components in React, it's common to bind event handlers
in the constructor or use arrow functions to ensure the correct `this` context. For example,
you might write `onClick={this.handleClick.bind(this)}` or `onClick={() =>
this.handleClick()}`.
3. Preventing Default Behavior: To prevent the default behavior of an event (e.g., preventing
form submission), you can call `event.preventDefault()` within the event handler. This is
often used in form submission to prevent the page from reloading.
4. Event Object: Event handlers receive an event object as their argument, which contains
information about the event, such as the target element, type of event, and more. You can
access properties and methods on this object to handle the event.
Form Submission:
1. Form Submission Handling: In React, you can handle form submissions using the
`onSubmit` event of the `<form>` element. When the user submits the form, you can intercept
the event, prevent the default behavior (page reload), and process the form data in your event
handler.
2. Data Handling: After intercepting the form submission event, you can access the form
elements' values from the component's state and perform actions like data validation, sending
data to a server, or updating the UI.

CONCULSION: We have implemented concepts of form and events in react.


Code:
RegistrationForm.js
App.js
import React from 'react';
import './App.css';
import RegistrationForm from './RegistrationForm';

function App() {
return (
<div className="App">
<RegistrationForm />
</div>
);
}

export default App;


LAB ASSGINMENT- 7a
Aim : WAP to implement ReactJS Router. Create more than two class or functional
components and implement program for Routing using browser router.
Lab Outcome :
LO5: To orient students to React for developing front end applications.
Theory :
React Router is a powerful library for handling routing in React applications. It allows you to
create single-page applications (SPAs) where different components are displayed based on
the URL, enabling navigation without refreshing the entire page. React Router uses the
`BrowserRouter` component as one of its routing mechanisms. Let's explore how to use
`BrowserRouter` in a React application:
1. Installation:
First, make sure you have React and React Router installed. You can install React
Router using npm or yarn: npm install react-router-dom
2. Importing BrowserRouter:
In your React application, import `BrowserRouter` from 'react-router-dom':
`javascript
import { BrowserRouter } from 'react-router-dom';
3. Wrapping the App Component:
Wrap your entire application or the root component (usually `App.js`) with the
`BrowserRouter` component. This should be done in your main entry file :

Here's how `BrowserRouter` works in this context:

1. `BrowserRouter` Component: The ```<BrowserRouter>` component wraps the


entire application. It provides the context for routing and is responsible for
synchronizing the application's UI with the URL.

2. `Navbar` Component: This component is rendered outside of the ``<Routes>``


component, which means it will appear on every page of your application. It likely
contains navigation links (e.g., Home, Contact, Brands, Registration), allowing users
to navigate to different parts of your app.

3. `Routes` Component: Inside the ``<BrowserRouter>``, the ``<Routes>`` component


is used to define the route configuration for your application. It acts as a container
for individual ```<Route>` components.

4. `Route` Components: Each `<Route>` ` component specifies how a particular URL


should map to a React component. For example: -
The <Route>` `` with `path="/" element={}` indicates that when the URL is exactly "/", the
`Home` component should be rendered. –
The `<Route>` ` with `path="/contact" element={}` maps the "/contact" URL to the
`Contact` component, and so on.
By using `BrowserRouter`, you enable client-side routing. When a user clicks a link or
enters a URL, React Router will determine which component to render based on the
URL's path. This approach provides a seamless user experience without full page reloads.

Conclusion : In conclusion, BrowserRouter is a fundamental component in React Router


that manages the routing of your application. It allows you to define routes using ``
components, making it easy to map URLs to specific components and create a dynamic
and responsive user interface
CODE:
LAB ASSGINMENT -7B
Aim: Write a Program to implement the concept of React Hooks.
LAB OUTCOME:
LO5- Construct front end application using React.
THEORY:
React Hooks are a feature introduced in React 16.8 that allow you to use state and other
React features in functional components, which were previously limited to class
components. Before Hooks, you had to use class components to manage state and lifecycle
methods. With Hooks, you can write more concise and reusable code in functional
components.
Here are some commonly used React Hooks:

• useState: Allows functional components to manage state. It takes an initial state


value and returns an array with the current state value and a function to update it.

• useEffect: Enables you to perform side effects in functional components. It takes a


function that contains the code for the side effect and an optional dependency array
to control when the effect runs.
• useContext: Allows you to access the context of a parent component in a functional
component. It takes a context object created by the React.createContext function.

• useReducer: A more advanced alternative to useState for managing complex state


logic. It takes a reducer function and an initial state and returns the current state and
a dispatch function to update it.
Functions:
React Hooks serve several key functions in React applications:

1. State Management in Functional Components: Prior to Hooks, state management


in functional components was limited. With the `useState` Hook, functional
components can now manage their own state. This allows you to create and
manipulate component-specific state without the need for class components.

2. Side Effects in Functional Components: The `useEffect` Hook enables functional


components to perform side effects, such as data fetching, DOM manipulation, and
subscriptions. This function mimics the behavior of lifecycle methods in class
components, but it's more expressive and composable.

3. Reusable Logic: Hooks encourage the creation of custom Hooks, which are
reusable pieces of stateful logic that can be shared across multiple components. This
promotes code reuse and cleaner code organization.

4. Simplifying Component Logic: Hooks help simplify complex component logic by


allowing you to split it into smaller, more manageable pieces. This leads to cleaner
and more maintainable code.

5. Encapsulation of Concerns: Hooks allow you to encapsulate related logic into


separate functions (custom Hooks) without the need for class-based HOCs (Higher-
Order Components) or render props, making your codebase more modular.

6. Elimination of Class Components: While class components are still supported in


React, Hooks provide an alternative way to write components that is more consistent
and easier to understand, potentially reducing the need for class components in
modern React applications.

7. Improved Code Readability: Hooks can lead to cleaner and more readable code
since the logic for a particular aspect of a component (e.g., state, effects) can be
contained within a single function. This reduces the need for scattered logic across
different lifecycle methods.

8. Functional Approach: Hooks fit naturally into the functional programming


paradigm, making React components more functional in nature. This can lead to
more predictable and easier-to-reason-about code.

9. Better Developer Experience: Hooks provide a more consistent and predictable


way to handle state and effects in React, which can enhance the developer
experience by reducing cognitive overhead.
10. Improved Testing: Functional components with Hooks are often easier to test
because you can isolate and test individual pieces of logic more effectively, thanks to
their functional nature.

In summary, React Hooks play a crucial role in modern React development by


simplifying and enhancing the capabilities of functional components. They provide a
more flexible and expressive way to handle state and side effects, leading to cleaner,
more maintainable, and more reusable code.

Conclusion:
React Hooks are used in React applications to simplify state management and side effect
handling in functional components. They provide a more flexible and concise way to manage
component logic.
Code:
Lab Assignment – 8
Aim: WAP to implement the calculator on commandline REPL.
Lab Outcome:
LO5: To orient students to React for developing front end applications.
Theory:
Node.js Calculator Using REPL (Command-Line Input)
1. REPL (Read-Eval-Print Loop): The program utilizes a REPL environment, which stands for
Read-Eval-Print Loop. This is an interactive command-line interface where users can input
commands or expressions, and the system immediately evaluates and returns results. It's
commonly used for experimentation, testing, and quick code execution.
2. Importing Modules: The program begins by importing the 'readline' module, which is a
core Node.js module for reading input from the user in the command line. This module
provides an interface for user interaction.
3. Creating the Readline Interface: An instance of the 'readline' interface is created,
specifying that it should read input from 'stdin' (standard input) and display output in
'stdout' (standard output). The 'terminal: false' option is set to disable certain terminal-
specific features.
4. User Input and Prompts: The program uses the 'rl.question' function to prompt the user
for input in a series of steps. It starts by asking for the first number, then the second number,
and finally the desired mathematical operation (addition, subtraction, multiplication, or
division).
5. Parsing User Input: After gathering user input, the program parses the entered values into
numeric format (floats) to ensure they are suitable for mathematical operations. This step
involves using 'parseFloat' to convert the input.
6. Mathematical Operations: Depending on the user's chosen operation, the program
performs the corresponding mathematical calculation (e.g., addition, subtraction,
multiplication, or division). This is achieved using conditional statements, such as a 'switch'
statement, to determine the operation and execute the appropriate calculation.
7. Result Display: The calculated result is then displayed on the command line for the user
to see. It provides immediate feedback on the outcome of the operation.
8. Error Handling: The program includes error handling to address potential issues. For
instance, it checks for invalid inputs (non-numeric values) and handles division by zero to
prevent errors and crashes.
9. Interactive User Experience: Users interact with the program by entering input at each
prompt, and the program responds with real-time feedback, making it a user-friendly
calculator tool.
Conclusion:
In summary, the Node.js calculator program demonstrates the principles of a REPL
environment, allowing users to interactively input mathematical operations and receive
immediate results.

OUTPUT:
LAB ASSIGNMENT 9

Aim: Write a program to implement


a. Create React refs
b. How to access Refs
c. Forward Refs
d. Callback Refs.

Lab Outcome:
LO5 – To orient students to React for developing front end applications.

Theory:

React is a popular JavaScript library for building user interfaces, and it provides
various tools and patterns to efficiently manage and manipulate the Document
Object Model (DOM) elements. One of these tools is React Refs, which allow
developers to access and interact with DOM elements directly. With the introduction
of React Hooks, working with refs has become more accessible and intuitive. In this
guide, we'll explore how to create and use React refs effectively using functional
components and hooks.

a. Creating React Refs:


React Refs are objects that provide a way to access and interact with DOM
elements directly. In functional components, you can create refs using the
`useRef` hook. Here's how to create a ref:
```javascript
const myRef = useRef(null);
```
The `useRef` hook initializes the `myRef` variable with the `current` property set
to `null`. You can attach this ref to a DOM element by assigning it as a `ref`
attribute in the JSX.

b. How to Access Refs:


Once you've created a ref, you can access and manipulate the corresponding
DOM element. To access the DOM element, you can use the `.current` property
of the ref. For example:
```javascript c
onst element = myRef.current;
if (element) { // Access and manipulate the DOM element } ``

It's important to check if the element exists before accessing and manipulating it
because the `current` property may initially be `null`.
c. Forward Refs:
React allows you to forward refs from a parent component to a child component.
This is particularly useful when you want to access a child's DOM element from a
parent component. To create a forward ref, use the `React.forwardRef` function:

```javascript
const ChildComponent = React.forwardRef((props, ref) => {
// JSX for child component
return <input ref={ref} /> ; });
```
In this example, the `ChildComponent` accepts a `ref` parameter and attaches it
to the `input` element. You can then use this forwarded ref in a parent
component:

```javascript

function ParentComponent() {
const childRef = useRef(null);

// Attach ref to the child component return ;


} ```

Now, `childRef.current` refers to the `input` element inside `ChildComponent`.

d. Callback Refs:
Callback refs are another way to work with refs in React. Instead of using the
`useRef` hook, you define a function that receives the DOM element as an
argument and stores it as a variable. Here's how to create and use a callback ref:
```javascript
let myRef = null;
const setMyRef = (element) => {
myRef = element; }; ``

In this example, `setMyRef` is a callback function that receives the DOM element
as an argument and assigns it to the `myRef` variable. You can then use `myRef`
to access and manipulate the DOM element. Callback refs are typically defined
inside the functional component.

React Hooks and functional refs provide a flexible and powerful way to work with
DOM elements in your React applications. Whether you're creating refs,
accessing DOM elements, forwarding refs to child components, or using callback
refs, these techniques empower you to build dynamic and interactive user
interfaces with ease.
Conclusion: In conclusion, React Hooks and functional refs offer a streamlined
approach to managing DOM elements in React applications, enhancing
accessibility and ease of use. These tools empower developers to create
dynamic and interactive user interfaces with efficiency and flexibility
LAB ASSIGNMNENT -10
AIM: Write a program in Node JS to
a. Create a file
b. Read the data from file
c. Write the data to a file
d. Rename a file
e. Append data to a file
f. Delete a file
LAB OUTCOME:
LO6 – Construct Backend Application using Node.js / Express.
THEORY:
Node.js is a runtime environment for executing JavaScript code outside of a web browser. It
is built on the V8 JavaScript engine from Google and is designed to be used for server-side
programming. Here are some key theoretical concepts and principles related to Node.js:
1. Non-Blocking and Asynchronous: One of the fundamental principles of Node.js is its non-
blocking and asynchronous nature. It uses an event-driven, single-threaded architecture that
allows it to handle many concurrent connections without blocking the execution of other
code. This makes it highly efficient for I/O-intensive operations like reading and writing to
files or making network requests.
2. Event Loop: Node.js relies on an event loop to manage asynchronous operations. The
event loop continuously checks for pending events (such as I/O operations or timers) and
executes callbacks when events are ready. This event-driven model is central to Node.js's
ability to handle concurrency.
3. Common JS Modules: Node.js uses the CommonJS module system for organizing and
managing code. Modules allow developers to break their code into reusable and
maintainable pieces. You can use the `require` function to import modules, and you can
create your own modules using `module.exports`.
4. npm (Node Package Manager):npm is the package manager for Node.js. It provides a vast
ecosystem of open-source libraries and tools that you can easily integrate into your Node.js
projects. You can use `npm` to install, manage, and share packages.
5. Single Thread with Worker Threads: While Node.js is single-threaded, it offers the
`worker_threads` module to create and manage multiple threads for CPU-intensive tasks.
This allows developers to take advantage of multi-core processors when needed.
6. Event Emitters: Many core Node.js modules and third-party libraries use event emitters to
handle and trigger events. Event emitters are a key part of creating custom event-driven
functionality in Node.js.
7. Streams: Node.js provides a built-in mechanism for working with streams of data. Streams
are useful for handling large datasets or real-time data. They can be readable (for input) or
writable (for output).
8. Error Handling: Due to its asynchronous nature, error handling in Node.js often relies on
callbacks and promises. Developers need to be mindful of handling errors correctly, and ther
are conventions for passing errors as the first argument to callbacks.
9. Blocking vs. Non-Blocking Code: Developers should be aware of the potential for blocking
code that can slow down an application. Careful design, asynchronous patterns, and utilizing
non-blocking functions can help avoid these issues.
10. Security: Node.js applications should follow best practices for security, such as input
validation, proper authentication and authorization, and keeping dependencies up to date.
These are some of the theoretical concepts and principles that form the foundation of
Node.js. Understanding these concepts is crucial for effectively developing applications with
Node.js.
CODE:
COCULISON:
This assignment provided practical knowledge for working with files and understanding the
core principles of Node.js, which are crucial for building efficient and secure server-side
applications.
LAB ASSIGNMENT 11

Aim: Create a web application that performs CRUD operations (database connectivity).

Theory:

CRUD operations

CRUD operations, which stand for Create, Read, Update, and Delete, are fundamental actions
in web applications that manipulate data. In the context of a To-Do List web app built with React
(a JavaScript library for building user interfaces) and Express.js (a Node.js framework for
building web applications), here's a short note on how these operations might be implemented:

1. Create (C):

- In your React frontend, provide a user interface where users can input and submit new
tasks.

- When a user submits a new task, send an HTTP POST request to your Express.js backend.

- In your Express.js backend, create a route and a handler to receive the POST request,
extract the task data, and add it to your database or storage.

- Return a response to acknowledge the successful creation of the task.

2. Read (R):

- Display the list of tasks on the React frontend, fetching the data from your Express.js
backend.

- Create an HTTP GET request in React to retrieve the list of tasks from your Express.js API.

- In your Express.js backend, set up a route and handler to respond to the GET request by
retrieving tasks from your database and sending them as a JSON response to the frontend.

- Display the tasks in your React component.

3. Update (U):

- Allow users to edit existing tasks on the React frontend by providing an edit interface.

- When a user edits a task, send an HTTP PUT request to your Express.js backend, including
the updated task data.

- In your Express.js backend, create a route and handler to receive the PUT request, update
the corresponding task in your database, and send a response indicating success.
4. Delete (D):

- Implement a mechanism in your React frontend to allow users to delete tasks, typically by
clicking a delete button next to each task.

- When a user requests to delete a task, send an HTTP DELETE request to your Express.js
backend, specifying the task to delete.

- In your Express.js backend, set up a route and handler to process the DELETE request,
remove the specified task from your database, and send a success response.

By implementing these CRUD operations, you enable users to interact with your To-Do List web
app effectively, allowing them to create, read, update, and delete tasks seamlessly. This
combination of React and Express.js provides a powerful platform for building responsive and
dynamic web applications.

MERN stack

The MERN stack, an acronym for MongoDB, Express.js, React, and Node.js, represents a
powerful and popular technology stack for building modern web applications.

MongoDB serves as the database component, offering a NoSQL, document-oriented storage


system. Its flexibility and scalability make it an ideal choice for managing application data.

Express.js, a web application framework for Node.js, functions as the backend server. It
simplifies tasks like routing, middleware integration, and handling HTTP requests and
responses, allowing for efficient backend development.

React, developed by Facebook, is the cornerstone of the frontend. This JavaScript library excels
in constructing user interfaces, leveraging a component-based architecture to create reusable
UI elements. It enables developers to build interactive, responsive user experiences.

Node.js, a runtime environment, empowers JavaScript to run on the server side. It boasts an
event-driven, non-blocking architecture, making it suitable for real-time and scalable
applications. When paired with Express.js, it creates a robust backend foundation.

The MERN stack offers several advantages, including full-stack JavaScript development,
real-time capabilities, scalability, a vibrant community, and rapid development. It's favored by
developers for its efficiency, allowing for quicker prototyping and development of web
applications that require flexibility, real-time updates, and a unified JavaScript codebase for both
frontend and backend components. In summary, the MERN stack is a versatile and widely
embraced technology stack for constructing modern web applications.
Database connectivity

Connecting to MongoDB, a NoSQL database, is a fundamental step in building applications that


require data storage and retrieval. Here’s the method for database connectivity using MongoDB:

1. Installation: Start by installing MongoDB on your local machine or setting up a remote


MongoDB server. MongoDB provides installation guides for various platforms.

2. MongoDB Drivers: Choose a MongoDB driver or library that suits your programming language
or framework. Popular options include the official MongoDB driver for JavaScript, Mongoose (an
Object Data Modeling library for Node.js), and various drivers for other languages like Python,
Java, and Ruby.

3. Connection Configuration: Configure your application to connect to the MongoDB database.


You'll typically need to specify connection parameters such as the server address, port, and
authentication credentials (username and password).

4. Connection Establishment: Use the chosen driver's API to establish a connection to the
MongoDB database. In most cases, you'll create a client or connection object that manages the
connection.

5. Database Operations: Once connected, you can perform various database operations,
including inserting, updating, querying, and deleting data. These operations are executed using
the driver's API.

6. Error Handling: Implement error-handling mechanisms to gracefully handle connection errors,


database exceptions, and other potential issues that may arise during interactions with
MongoDB.

7. Closing the Connection: It's good practice to close the database connection when your
application no longer needs it, typically during the application's shutdown process.

8. Security: Ensure that you follow security best practices, including properly configuring
authentication, authorization, and network access controls to protect your MongoDB database
from unauthorized access.

Connecting to MongoDB allows your application to store, retrieve, and manipulate data
efficiently. Whether you're building a web application, mobile app, or any software that relies on
data persistence, MongoDB's flexibility and scalability make it a popular choice for developers.
import mongoose from "mongoose";
import dotenv from 'dotenv';

dotenv.config();

const USERNAME = process.env.DB_USERNAME;


const PASSWORD = process.env.DB_PASSWORD;

const Connection = () => {

const MONGODB_URI =
`mongodb+srv://Rudrani26:[email protected]/?retryWrite
s=true&w=majority&appName=AtlasApp`;

mongoose.connect(MONGODB_URI, { useNewUrlParser: true });

mongoose.connection.on('connected', () => {
console.log('Database connected Successfully');
})

mongoose.connection.on('disconnected', () => {
console.log('Database disconnected');
})

mongoose.connection.on('error', (error) => {


console.log('Error while connecting with the database ',
error.message);
})
}
export default Connection;

import mongoose from "mongoose";

const TodoSchema = new mongoose.Schema({


data: {
type: String,
required: true
},
done: {
type: Boolean,
default: false
},
createdAt: {
type: Date,
default: Date.now
}
})

const todo = mongoose.model('tasks', TodoSchema);

export default todo;

Here's a short explanation of what's happening in each part of the code:

1. dotenv Configuration:
- You import the `dotenv` library and use it to load environment variables from a `.env` file.
- You retrieve the database username and password from these environment variables and
store them in `USERNAME` and `PASSWORD` constants.

2. Connection to MongoDB:
- You define a function called `Connection` that connects to a MongoDB database using
Mongoose.
- Inside this function, you construct the `MONGODB_URI` by including the username and
password retrieved from the environment variables, as well as other connection options such as
the MongoDB Atlas cluster URL and the application name.
- You use `mongoose.connect` to establish a connection to the MongoDB database using the
provided URI.
- You set up event listeners for various connection events:
- `'connected'`: This event is triggered when the connection to the database is successfully
established. It logs a success message to the console.
- `'disconnected'`: This event is triggered when the connection to the database is
disconnected. It logs a message to the console.
- `'error'`: This event is triggered when an error occurs during the connection process. It logs
an error message to the console.

3. Todo Schema:
- You import the `mongoose` library again.
- You define a Mongoose schema called `TodoSchema` for your "tasks" collection.
- The schema has three fields:
- `data`: A string field that is required.
- `done`: A boolean field with a default value of `false`.
- `createdAt`: A date field with a default value of the current date and time.

4. Todo Model:
- You create a Mongoose model called `todo` for the "tasks" collection using the
`mongoose.model` method. The first argument is the name of the collection ('tasks'), and the
second argument is the schema (`TodoSchema`).

Overall, this code sets up a connection to a MongoDB database, defines a schema for a "tasks"
collection, and creates a Mongoose model for interacting with documents in that collection. This
code appears to be part of a larger application that can perform CRUD (Create, Read, Update,
Delete) operations on tasks in the MongoDB database.

Conclusion:

In summary, the provided code establishes a connection to a MongoDB database using


Mongoose in a Node.js application. It also defines a schema and model for a "tasks" collection.
This foundation is crucial for building a web application that can perform CRUD operations—
Create, Read, Update, and Delete—on tasks. By integrating this backend with a React
frontend and Express.js, you can create a powerful and responsive To-Do List web application,
enabling users to interact with and manage their tasks effectively. This combination of
technologies exemplifies the MERN stack, a popular choice for modern web development,
offering flexibility, scalability, and a unified JavaScript codebase.

You might also like