NRDJS
NRDJS
AND
TECHNOLOGICAL INSTITUTE
Aushapur, Ghatkesar, Medchal-501301
DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
1 | Page
INDEX
S. No Name of the Experiment
Build a responsive web application for shopping cart with registration, login,
1 catalog and cart pages using CSS3 features, flex and grid.
2 Make the above web application responsive web application using Bootstrap
framework.
3 Use JavaScript for doing client – side validation of the pages implemented in
experiment 1 and experiment 2.
2 | Page
Course Objectives:
● To implement the static web pages using HTML and do
client side validation using JavaScript.
● To design and work with databases using Java
● To develop an end to end application using java full stack.
● To introduce Node JS implementation for server side
programming.
● To experiment with single page application development
using React.
Course Outcomes:
At the end of the course, the student will be able to,
● Build a custom website with HTML, CSS, and Bootstrap
and little JavaScript.
● Demonstrate Advanced features of JavaScript and learn
about JDBC
● Develop Server – side implementation using Java
technologies like
● Develop the server – side implementation using Node JS.
● Design a Single Page Application using React.
3 | Page
1. Build a responsive web application for shopping cart with registration,
login, catalog and cart pages using CSS3 features, flex and grid. index.html
PROGRAM:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shopify</title>
<link rel="stylesheet" href="./css/style.css">
<link rel="stylesheet" href="./css/responsive.css">
<link href="https://fonts.googleapis.com/css2?
family=Poppins:ital,wght@1,900&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/1ba2cf90f3.js"
crossorigin="anonymous"></script>
<link rel="shortcut icon" href="./assests/Citycons_bag-512.webp" type="image/x-icon">
</head>
<body>
<section>
<nav>
<span><a href="index.html"><i class="fas fa-shopping-bag"></i>shopping
cart</a></span>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="signup.html">signup</a></li>
<li><a href="login.html">login</a></li>
<li><span onclick="openBucket()"><i class="fas fa-shopping-cart"></i></span>
<span class="items-count"></span>
</li>
4 | Page
</ul><span onclick="openBucket()" class="cart-icon"><i class="fas
fa-shoppingcart"></i></span>
</nav>
<main class="fruits-side">
<span>Buy Fruits</span>
<button><a href="fruit-aisle.html">Shop Now <i class="fas
fa-caretright"></i></a></button>
</main>
<div class="cart">
<header><span><a href="index.html"><i class="fas fa-shopping-bag"></i>
Shopify</a></span><span
class="exit"><i class="fas fa-times"></i></span></header>
<main>
<ol>
<li>Item-Name</li>
<li>Qty</li>
<li>Total</li>
</ol>
<section>
<ul id="ul"></ul>
</section>
</main>
</div>
</section>
<script>
consttop_items_count = document.querySelector('.items-count'),
bottom_items_count = document.querySelector('.bottom-items-count'),
exit = document.querySelector('.exit'),
bucket = document.querySelector('.cart').style;
top_items_count.innerHTML = 0;
bottom_items_count.innerHTML = 0;
5 | Page
function openBucket() {
bucket.visibility = "visible";
bucket.opacity = "1";
bucket.zIndex = "9";
bucket.transition = "all 0.5s";
}exit.addEventListener('click', () => {
bucket.visibility = "hidden";
bucket.opacity = "0";
bucket.zIndex = "-9";
bucket.transition = "all 0.5s";
});
top_items_count.innerHTML = count;
bottom_items_count.innerHTML = count;
</script>
</body>
</html>
Registration: signup.html
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<title>Sign Up</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="signup_style.css" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/fontawesome.min.css"
/>
<link
6 | Page
href="https://fonts.googleapis.com/css?family=Titillium+Web:400,300,600"
rel="stylesheet"
type="text/css"
/>
<script
src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottieplayer.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css"
integrity="sha384-
vp86vTRFVJgpjF9jiIGPEEqYqlDwgyBgEF109VFjmqGmIY/Y4HV4d3Gp2irVfcrp"
crossorigin="anonymous">
</head>
<div class="login-page">
<div class="form">
<form>
<lottie-player
src="https://assets4.lottiefiles.com/datafiles/XRVoUu3IX4sGWtiC3MPpFnJvZNq7
lVWDCa8LSqgS/profile.json"
background="transparent"
speed="1"
style="justify-content: center"
loop
autoplay
></lottie-player>
<input type="text" placeholder="full name" />
<input type="text" placeholder="email address" />
<input type="text" placeholder="pick a username" />
<input type="password" id="password" placeholder="set a password" />
<i class="fas fa-eye" onclick="show()"></i>
<br>
<br>
</form>
7 | Page
<form class="login-form">
<button type="button" onclick="window.location.href='login.html'">
SIGN UP
</button>
</form>
</div>
</div>
</body>
<script>
function show() {
var password = document.getElementById("password");
var icon = document.querySelector(".fas");
// ========== Checking type of password ===========
if (password.type === "password") {
password.type = "text";
} else {
password.type = "password";
}
}
</script>
</html>
</html>
SignIn : login.html
<!DOCTYPE HTML>
<html lang="en" >
<html>
<head>
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
8 | Page
<link rel="stylesheet" type="text/css" href="login_style.css">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css">
<link href='https://fonts.googleapis.com/css?family=Titillium+Web:400,300,600'
rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Titillium+Web:400,300,600'
rel='stylesheet' type='text/css'>
<script
src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottieplayer.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css"
integrity="sha384-
vp86vTRFVJgpjF9jiIGPEEqYqlDwgyBgEF109VFjmqGmIY/Y4HV4d3Gp2irVfcrp"
crossorigin="anonymous">
</head>
<div class="login-page">
<div class="form">
<form>
<lottie-player
src="https://assets4.lottiefiles.com/datafiles/XRVoUu3IX4sGWtiC3MPpFnJvZNq7lV
WDCa8LSqgS/profile.json" background="transparent" speed="1" style="justifycontent:
center;" loop autoplay></lottie-player>
<input type="text" placeholder=" username"/>
<input type="password" id="password" placeholder=" password"/>
<i class="fas fa-eye" onclick="show()"></i>
<br>
<br>
<button>LOGIN</button>
<p class="message"></p>
</form>
<form class="login-form">
<button type="button" onclick="window.location.href='signup.html'">SIGN
9 | Page
UP</button>
</form>
</div>
</div>
<script>
function show(){
var password = document.getElementById("password");
var icon = document.querySelector(".fas")
// ========== Checking type of password ===========
if(password.type === "password"){
password.type = "text";
}
else {
password.type = "password";
}
};
</script>
</body>
</html>
10 | Page
crossorigin="anonymous"></script>
<link rel="shortcut icon" href="./assests/Citycons_bag-512.webp" type="image/xicon">
</head>
<body>
<section>
<nav>
<span><a href="index.html"><i class="fas fa-shopping-bag"></i> Shopify
shopping cart</a></span>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="signup.html">signup</a></li>
<li><a href="login.html">login</a></li>
<li><span onclick="openBucket()"><i class="fas fa-shoppingcart"></i></span>
<span class="items-count"></span>
</li>
</ul>
<span onclick="openBucket()" class="cart-icon"><i class="fas
fa-shoppingcart"></i></span>
</nav>
<main>
<div class="items item-1" data-item="Apples" data-price="100"></div>
<div class="items item-2" data-item="Lemons" data-price="200"></div>
<div class="items item-3" data-item="Strawberries" data-price="300"></div>
<div class="items item-4" data-item="Bananas" data-price="400"></div>
</main>
<div class="cart">
<header><span><a href="index.html"><i class="fas fa-shopping-bag"></i>
Shopify</a></span><span
class="exit"><i class="fas fa-times"></i></span></header>
<main>
<ol>
11 | Page
<li>Item-Name</li>
<li>Qty</li>
<li>Total</li>
</ol>
<section>
<ul id="ul">
</ul>
</section>
</main>
</div>
</section>
<script src="./js/script3.js"></script>
</body>
</html>
Responsive.css
@media (min-width: 0px) and (max-width: 425px) {
section > nav {
grid-template-columns: auto 13vw;
}
section > nav >ul {
display: none;
}
.cart-icon {
color: #323232;
font-size: 1.3rem;
}
.fruits-side > span {
font-size: 3.3rem;
padding-top: 80px;
}
12 | Page
.fruits-side > button {
height: 10vh;
width: 53vw;
font-size: 1.2rem;
letter-spacing: 1px;
margin-bottom: 30px;
}
.cart {
position: fixed;
height: 100vh;
width: 100%;
top: 0%;
left: 0%;
transform: scale(0.9);
}
.cart> main >ol>li:nth-child(1) {
padding: 0px 12px;
}
}
@media (min-width: 426px) and (max-width: 1023px) {
section > nav {
grid-template-columns: auto 60vw;
}
section > nav > span {
font-size: 1.6rem;
}
section > nav >ul> li > a {
font-size: 1.1rem;
}
.fruits-side > button {
13 | Page
height: 10vh;
width: 25vw;
font-size: 1.2rem;
letter-spacing: 1px;
margin-bottom: 30px;
}
.cart {
position: fixed;
height: 100vh;
width: 100%;
top: 0%;
left: 0%;
transform: scale(0.9);
}
.cart> main >ol>li:nth-child(1) {
padding: 0px 12px;
}
section > footer {
grid-template-columns: auto 60vw;
}
section > footer >ul> li {
padding: 10px 15px;
}
}
Style.css
*,
body {
margin: 0;
padding: 0;
list-style: none;
14 | Page
text-decoration: none;
outline: none;
letter-spacing: 1px;
transition: all 0.5s;
color: inherit;
scroll-behavior: smooth;
font-family: "Poppins", sans-serif;
}
section {
position: relative;
width: 100%;
display: grid;
grid-template-columns: 0.99fr;
grid-template-rows: 15vh repeat(3, 80vh) 15vh;
align-content: space-around;
justify-content: space-evenly;
}
section > nav {
display: grid;
grid-template-columns: 15vw 50vw;
grid-template-rows: 0.8fr;
align-content: space-around;
justify-content: space-around;
background-color: whitesmoke;
}
section > nav > span {
display: flex;
align-items: center;
justify-content: space-evenly;
font-weight: bold;
15 | Page
font-size: 2rem;
color: grey;
text-transform: capitalize;
}
section > nav > span > a >i {
color: #323232;
}
section > nav >ul {
display: flex;
align-items: center;
justify-content: space-evenly;
}
section > nav >ul> li {
position: relative;
}
section > nav >ul> li > a {
font-weight: bold;
font-size: 1.3rem;
letter-spacing: 1px;
color: grey;
}
section > nav >ul> li > a >i {
color: #323232;
font-size: 2rem;
}
.cart-icon{
display: none;
}
.items-count {
position: absolute;
16 | Page
padding: 5px;
background-color: red;
color: white;
font-weight: bold;
font-size: 0.9rem;
border-radius: 30px;
top: -40%;
}
.fruits-side {
background-image: url("../assests/62.jpg");
background-size: 100% 100%;
display: grid;
align-content: space-around;
justify-content: space-evenly;
}
.fruits-side > span {
font-weight: bold;
font-size: 8rem;
color: white;
text-transform: capitalize;
padding-top: 80px;
}
.fruits-side > button {
height: 8.5vh;
width: 13vw;
background-color: transparent;
border: 1.5px solid white;
border-radius: 10px;
font-weight: bold;
font-size: 1.2rem;
17 | Page
color: white;
letter-spacing: 1px;
justify-self: center;
margin-bottom: 30px;
}
.fruits-side > button > a {
display: flex;
align-items: center;
justify-content: space-evenly;
}
.fruits-side >button:hover {
transition: all 0.5s;
cursor: pointer;
background-color: white;
border: none;
color: rgba(0, 0, 0, 0.5);
}
.fruits-side > button > a >i {
font-size: 1.8rem;
}
.bottom-items-count {
position: absolute;
padding: 5px;
background-color: red;
color: white;
font-weight: bold;
font-size: 0.9rem;
border-radius: 30px;
bottom: 40%;
}
18 | Page
.cart {
position: fixed;
height: 98.5%;
width: 25vw;
background-color: whitesmoke;
top: 0.5%;
right: 0.5%;
display: grid;
grid-template-columns: 0.95fr;
grid-template-rows: 10vh 60vh 10vh;
align-content: space-around;
justify-content: space-evenly;
box-shadow: 0px 0px 10px 5px rgba(0, 0, 0, 0.5);
border-radius: 5px;
opacity: 0;
visibility: hidden;
z-index: -9;
transition: all 0.5s;
}
.cart> header {
display: flex;
align-items: center;
justify-content: space-around;
}
.cart> header > span {
display: flex;
align-items: center;
justify-content: space-evenly;
font-weight: bold;
font-size: 1.5rem;
19 | Page
color: grey;
text-transform: capitalize;
}
.cart> header > span > a >i {
color: #323232;
}
.exit>i {
font-size: 2rem;
color: #323232;
cursor: pointer;
transition: all 0.5s;
}
.cart> main {
box-shadow: 0px 0px 10px 1px rgba(0, 0, 0, 0.5);
border-radius: 5px;
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 5vh 1fr;
align-content: space-around;
justify-content: space-evenly;
transition: all 0.5s;
}
.cart> main >ol {
display: flex;
align-items: center;
justify-content: space-around;
}
.cart> main >ol> li {
font-weight: lighter;
border: 1px solid rgba(0, 0, 0, 0.5);
20 | Page
padding: 0px 21px;
color: grey;
}
.cart> main > section {
overflow: scroll;
transition: all 0.5s;
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr;
align-content: space-around;
justify-content: space-evenly;
}
.cart> main > section >ul> li {
display: flex;
align-items: center;
justify-content: space-between;
height: 5vh;
border-bottom: 1px solid rgba(0, 0, 0, 0.5);
cursor: pointer;
transition: all 0.5s;
}
Style3.css
*,
body {
margin: 0;
padding: 0;
list-style: none;
text-decoration: none;
outline: none;
letter-spacing: 1px;
transition: all 0.5s;
21 | Page
color: inherit;
scroll-behavior: smooth;
font-family: "Poppins", sans-serif;
}
section {
width: 100%;
display: grid;
grid-template-columns: 0.99fr;
grid-template-rows: 15vh 90vh 15vh;
align-content: space-around;
justify-content: space-evenly;
transition: all 0.5s;
}
section > nav {
display: grid;
grid-template-columns: 15vw 50vw;
grid-template-rows: 0.8fr;
align-content: space-around;
justify-content: space-around;
background-color: whitesmoke;
}
section > nav > span {
display: flex;
align-items: center;
justify-content: space-evenly;
font-weight: bold;
font-size: 2rem;
color: grey;
text-transform: capitalize;
}
22 | Page
section > nav > span > a >i {
color: #323232;
}
section > nav >ul {
display: flex;
align-items: center;
justify-content: space-evenly;
}
section > nav >ul> li {
position: relative;
}
section > nav >ul> li > a {
font-weight: bold;
font-size: 1.3rem;
letter-spacing: 1px;
color: grey;
}
section > nav >ul> li > a >i {
color: #323232;
font-size: 2rem;
}
.items-count {
position: absolute;
padding: 5px;
background-color: red;
color: white;
font-weight: bold;
font-size: 0.9rem;
border-radius: 30px;
top: -40%;
23 | Page
}
.cart-icon {
display: none;
}
section > main {
display: grid;
grid-template-columns: repeat(4, 23.5vw);
grid-template-rows: 55vh;
align-content: space-around;
justify-content: space-evenly;
}
.items {
border-radius: 5px;
position: relative;
transition: all 0.5s;
}
.item-1 {
background-image: url("../assests/fruit-img/close-up-photography-of-apples672101.jpg");
background-size: 100% 100%;
}
.item-1::after {
content: "Apples";
position: absolute;
bottom: -13.5%;
left: 0;
font-weight: bold;
font-size: 1.75rem;
color: #323232;
}
.item-1::before {
24 | Page
content: "Add To Cart";
position: absolute;
font-weight: bold;
font-size: 1.2rem;
color: white;
background-color: transparent;
padding: 10px;
border-radius: 20px;
cursor: pointer;
left: 27%;
top: 45%;
cursor: pointer;
opacity: 0;
visibility: hidden;
transition: all 0.5s;
border: 2px solid white;
}
.item-1:hover::before {
opacity: 1;
visibility: visible;
transition: all 0.5s;
}
.item-1:hover {
background-image: linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)),
url("../assests/fruit-img/close-up-photography-of-apples-672101.jpg");
}
.item-2 {
background-image: url("../assests/fruit-img/three-yellow-citrus-952360.jpg");
background-size: 100% 100%;
}
25 | Page
.item-2::after {
content: "Lemons";
position: absolute;
bottom: -13.5%;
left: 0;
font-weight: boldfont-size: 1.75rem;
color: #323232;
}
.item-2::before {
content: "Add To Cart";
position: absolute;
font-weight: bold;
font-size: 1.2rem;
color: white;
background-color: transparent;
padding: 10px;
border-radius: 20px;
cursor: pointer;
left: 27%;
top: 45%;
cursor: pointer;
opacity: 0;
visibility: hidden;
transition: all 0.5s;
border: 2px solid white;
}
.item-2:hover::before {
opacity: 1;
visibility: visible;
transition: all 0.5s;
26 | Page
}
.item-2:hover {
background-image: linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)),
url("../assests/fruit-img/three-yellow-citrus-952360.jpg");
}
.item-3 {
background-image: url("../assests/fruit-img/white-bowl-of-whole-strawberries89778.jpg");
background-size: 100% 100%;
}
.item-3::after {
content: "Strawberries";
position: absolute;
bottom: -13.5%;
left: 0;
font-weight: bold;
font-size: 1.75rem;
color: #323232;
.item-3::before {
content: "Add To Cart";
position: absolute;
font-weight: bold;
font-size: 1.2rem;
color: white;
background-color: transparent;
padding: 10px;
border-radius: 20px;
cursor: pointer;
left: 27%;
top: 45%;
cursor: pointer;
27 | Page
opacity: 0;
visibility: hidden;
transition: all 0.5s;
border: 2px solid white;
}
.item-3:hover::before {
opacity: 1;
visibility: visible;
transition: all 0.5s;
}
.item-3:hover {
background-image: linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)),
url("../assests/fruit-img/white-bowl-of-whole-strawberries-89778.jpg");
}
.item-4 {
background-image: url("../assests/fruit-img/yellow-bananas-61127.jpg");
background-size: 100% 100%;
}
.item-4::after {
content: "Bananas";
position: absolute;
bottom: -13.5%;
left: 0;
font-weight: bold;
font-size: 1.75rem;
color: #323232;
}
.item-4::before {
content: "Add To Cart";
position: absolute;
28 | Page
font-weight: bold;
font-size: 1.2rem
color: white;
background-color: transparent;
padding: 10px;
border-radius: 20px;
cursor: pointer;
left: 27%;
top: 45%;
cursor: pointer;
opacity: 0;
visibility: hidden;
transition: all 0.5s;
border: 2px solid white;
}
.item-4:hover::before {
opacity: 1;
visibility: visible;
transition: all 0.5s;
}
.item-4:hover {
background-image: linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)),
url("../assests/fruit-img/yellow-bananas-61127.jpg");
}
@media (min-width: 0px) and (max-width: 425px) {
section {
grid-template-rows: 15vh 250vh 15vh;
}
section > main {
grid-template-columns: repeat(1, 85vw);
29 | Page
grid-template-rows: repeat(4, 50vh);
}
.item-1::before,
.item-2::before,
.item-3::before,
.item-4::before {
padding: 10px 15px;
left: 20%;
top: 43%;
}
.item-1::after,
.item-2::after,
.item-3::after,
.item-4::after {
bottom: -18%;
font-size: 1.5rem
}
.item-4 {
margin-bottom: 10%;
}
}
@media (min-width: 426px) and (max-width: 1023px) {
section {
grid-template-rows: 15vh 140vh 15vh;
}
section > main {
grid-template-columns: repeat(2, 35vw);
grid-template-rows: repeat(2, 55vh);
}
.item-1::before,
30 | Page
.item-2::before,
.item-3::before,
.item-4::before {
padding: 10px 15px;
left: 20%;
top: 43%;
}
.item-1::after,
.item-2::after,
.item-3::after,
.item-4::after {
bottom: -18%;
font-size: 1.5rem;
}
}
OUTPUT:
31 | Page
32 | Page
33 | Page
2. Make the above web application responsive web application using Bootstrap
framework
PROGRAM:
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Bootstrap 4 - Shopping Cart</title>
<link rel="stylesheet" href="assets/bootstrap/bootstrap.min.css">
<script src="assets/js/jquery.min.js"></script>
<link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
<script src="assets/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="assets/css/style.css">
<link rel="icon" href="images/favicon.ico" type="image/x-icon" />
</head>
<body>
<!-- partial:index.partial.html -->
<!-- Nav -->
<nav class="navbar navbar-inverse bg-inverse fixed-top bg-faded">
<div class="row">
<div class="col">
<span data-toggle="modal" data-target="#cart">
<i class="fas fa-shopping-cart fa-2x fa-border icon-grey
zoom-sm"><span class="badge total-count"></span></i>
</span>
<button class="clear-cart btnbtn-danger ml-2" id="clearCart">
<i class="fas fa-undo"></i> Clear
</button>
</div>
34 | Page
</div>
</nav>
<!-- Main -->
<div class="container">
<br>
<h3 class="text-center">Bootstrap 4 - Shopping Cart</h3>
<hr>
<div class="row">
<div class="col-sm-12 col-md-6 col-xl-4">
<figure class="card card-product zoom">
<div class="img-wrap"><imgsrc="images/item-0.jpg" class="rounded p1"></div>
<figcaption class="info-wrap">
<h4 class="title">Beautiful dress</h4>
<p class="desc">Some small description goes here</p>
<div class="rating-wrap">
<div class="label-rating">132 reviews</div>
<div class="label-rating">154 orders </div>
<br/>
<small class="text-muted">★ ★
★ ★ ☆</small>
</div><!-- rating-wrap.// -->
</figcaption>
<div class="bottom-wrap">
<a href="" class="btnbtn-smbtn-primary float-right add-to-cart showtoast"
data-product_id="1" data-pimage="images/item-0.jpg" data-name="Beautiful dress"
data-price="220">
<i class="fas fa-shopping-cart"></i> Add to cart
</a>
<div class="price-wrap h5">
<span class="price-new">$220</span><del class="priceold">$300</del>
</div><!-- price-wrap.// -->
35 | Page
</div><!-- bottom-wrap.// -->
</figure>
</div><!-- col // -->
<div class="col-sm-12 col-md-6 col-xl-4">
<figure class="card card-product zoom">
<div class="img-wrap"><imgsrc="images/item-1.jpg" class="rounded p-1">
</div>
<figcaption class="info-wrap">
<h4 class="title">Elegant style</h4>
<p class="desc">Some small description goes here</p>
<div class="rating-wrap">
<div class="label-rating">132 reviews</div>
<div class="label-rating">154 orders </div>
<br/>
<small class="text-muted">★ ★
★ ★ ☆</small>
</div><!-- rating-wrap.// -->
</figcaption>
<div class="bottom-wrap">
<a href="" class="btnbtn-smbtn-primary float-right add-tocart show-toast"
data-product_id="2" data-pimage="images/item-1.jpg" data-name="Elegant
style" data-price="115">
<i class="fas fa-shopping-cart"></i> Add to cart
</a>
<div class="price-wrap h5">
<span class="price-new">$115</span><del
class="price-old">$180</del>
</div><!-- price-wrap.// -->
</div><!-- bottom-wrap.// -->
</figure>
</div><!-- col // -->
36 | Page
<div class="col-sm-12 col-md-6 col-xl-4">
<figure class="card card-product zoom">
<div class="img-wrap"><imgsrc="images/item-2.jpg" class="rounded p1"></div>
<figcaption class="info-wrap">
<h4 class="title">Modern fashion</h4>
<p class="desc">Some small description goes here</p>
<div class="rating-wrap">
<div class="label-rating">132 reviews</div>
<div class="label-rating">154 orders </div>
<br/>
<small class="text-muted">★ ★
★ ★ ☆</small>
</div><!-- rating-wrap.// -->
</figcaption>
<div class="bottom-wrap">
<a href="" class="btnbtn-smbtn-primary float-right add-tocart show-toast"
data-product_id="3" data-pimage="images/item-2.jpg" dataname="Modern fashion"
data-price="680">
<i class="fas fa-shopping-cart"></i> Add to cart
</a>
<div class="price-wrap h5">
<span class="price-new">$680</span><del
class="price-old">$980</del>
</div><!-- price-wrap.// -->
</div><!-- bottom-wrap.// -->
</figure>
</div><!-- col // -->
</div><!-- row.// -->
<div class="row p-2">
<p class="text-info font-weight-bold">
Easy to add to a new or existing project. Requires Bootstrap 4 Css&Js, Jquery, and
37 | Page
Fontawesome. Just add the resources <code class="text-danger">*/style.css</code> and
<code class="text-danger">*/script.js</code> to get going.
</p>
<p class="text-info font-weight-bold">
Customize the layout to your own preference. All you need is to provide the <kbd>Add
to Cart</kbd>buttton with the <code class="text-danger">data-product_id</code>, <code
class="text-danger">data-pimage</code>
<code class="text-danger">data-name</code>, and <code
class="text-danger">dataprice</code> attributes.
</p>
<p class="text-info font-weight-bold">
The cart form data is generated with the function <code
class="textdanger">displayCart()</code> in the <code class="text-danger">script.js</code>
code. You
can modify it to your own preference.
</p>
</div>
</div>
<!--container.//-->
<!-- Modal -->
<div class="modal fade" id="cart" tabindex="-1" role="dialog"
arialabelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<form action="index.html" method="get" class="cart-form">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel"><i class="fas fa-shoppingcart
text-black"></i> Shopping Cart</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
38 | Page
<div class="modal-body">
<table class="show-cart table">
</table>
<div class="font-weight-bold">Total price: $<span class="total-cart
textdanger"></span></div>
</div>
<div class="modal-footer">
<button type="button" class="btnbtn-danger" datadismiss="modal">Close</button>
<button type="submit" class="btnbtn-success">Checkout</button>
</div>
</form>
</div>
</div>
</div>
<!-- partial -->
<script src='assets/js/jquery.min.js'></script>
<script src="assets/js/script.js"></script>
39 | Page
script.js
// ************************************************
// Shopping Cart API
// ************************************************
var shoppingCart = (function() {
// =============================
// Private methods and propeties
// =============================
cart = [];
// Constructor
function Item(product_id, name, price, pimage, count) {
"use strict";
this.product_id = product_id;
this.name = name;
this.price = price;
this.pimage = pimage;
this.count = count;
}
// Save cart
function saveCart() {
"use strict";
sessionStorage.setItem('shoppingCart', JSON.stringify(cart));
}
// Load cart
function loadCart() {
"use strict";
cart = JSON.parse(sessionStorage.getItem('shoppingCart'));
}
if (sessionStorage.getItem("shoppingCart") != null) {
40 | Page
loadCart();
}
// =============================
// Public methods and propeties
// =============================
var obj = {};
// Add to cart
obj.addItemToCart = function(product_id, name, price, pimage, count) {
"use strict";
for(var item in cart) {
if(cart[item].product_id === product_id) {
cart[item].count ++;
saveCart();
return;
}
}
var item = new Item(product_id, name, price, pimage, count);
cart.push(item);
saveCart();
}
// Set count from item
obj.setCountForItem = function(product_id, count) {
"use strict";
for(var i in cart) {
if (cart[i].product_id === product_id) {
cart[i].count = count;
break;
}
}
41 | Page
};
// Remove item from cart
obj.removeItemFromCart = function(product_id) {
"use strict";
for(var item in cart) {
if(cart[item].product_id === product_id) {
cart[item].count --;
if(cart[item].count === 0) {
cart.splice(item, 1);
}
break;
}
}
saveCart();
}
// Remove all items from cart
obj.removeItemFromCartAll = function(product_id) {
"use strict";
for(var item in cart) {
if(cart[item].product_id === product_id) {
cart.splice(item, 1);
break;
}
}
saveCart();
}
// Clear cart
obj.clearCart = function() {
"use strict";
cart = [];
42 | Page
saveCart();
}
// Count cart
obj.totalCount = function() {
"use strict";
var totalCount = 0;
for(var item in cart) {
totalCount += cart[item].count;
}
return totalCount;
}
// Total cart
obj.totalCart = function() {
"use strict";
var totalCart = 0;
for(var item in cart) {
totalCart += cart[item].price * cart[item].count;
}
return Number(totalCart.toFixed(2));
}
// List cart
obj.listCart = function() {
var cartCopy = [];
for(i in cart) {
item = cart[i];
itemCopy = {};
for(p in item) {
itemCopy[p] = item[p];
}
43 | Page
itemCopy.total = Number(item.price * item.count).toFixed(2);
cartCopy.push(itemCopy)
}
return cartCopy;
}
// cart : Array
// Item : Object/Class
// addItemToCart : Function
// removeItemFromCart : Function
// removeItemFromCartAll : Function
// clearCart : Function
// countCart : Function
// totalCart : Function
// listCart : Function
// saveCart : Function
// loadCart : Function
return obj;
})();
// *****************************************
// Triggers / Events
// *****************************************
// Add item
$('.add-to-cart').on("click", function(event){
"use strict";
event.preventDefault();
var product_id = $(this).data('product_id');
var name = $(this).data('name');
var price = Number($(this).data('price'));
var pimage = $(this).data('pimage');
44 | Page
shoppingCart.addItemToCart(product_id, name, price, pimage, 1);
displayCart();
});
// Clear items
$('.clear-cart').on("click",function() {
"use strict";
shoppingCart.clearCart();
displayCart();
});
function displayCart() {
"use strict";
var cartArray = shoppingCart.listCart();
var output = "";
var total_order = 0;
for(var i in cartArray) {
total_order++;
output += "<div class='col-12'>"
+ "<div class='row justify-content-center'>"
+ "<div class='col-5'>"
+ "<div class='row'>"
+ "<div class='col-9 text-left'>"
+ "<imgsrc='" + cartArray[i].pimage + "' class='rounded-circle' width='50' height='50' />"
+ "<span class='text-info pl-3 font-weight-bold'>" + cartArray[i].name + "</span>"
+ "</div>"
+ "<div class='col-3'>"
+ "<span class='text-dark pl-2 mr-1'>(" + cartArray[i].price + ")</span>"
+ "</div>"
+ "</div>"
+ "</div>"
45 | Page
+ "<div class='col-4'>"
+ "<div class='input-group'><button class='minus-item input-group-addon btnbtn-primary'
dataproduct_id=" + cartArray[i].product_id + ">-</button>"
+ "<input type='number' class='item-count form-control' data-product_id='" +
cartArray[i].product_id + "' value='" + cartArray[i].count + "'>"
+ "<button class='plus-item btnbtn-primary input-group-addon' data-product_id=" +
cartArray[i].product_id + ">+</button></div>"
+ "</div>"
+ "<div class='col-3'>"
+ "<button class='delete-item btnbtn-danger' data-product_id=" + cartArray[i].product_id +
">X</button>"
+ "<span class='text-dart pl-2'><kbd>" + cartArray[i].total + "</kbd></span>"
+ "</div>"
+ "</div>"
+ "</div>"
+ "<div class='row' id='hedden-fields'><input type = 'hidden' class='sr-only'
name='ProductID[]'
id='ProductName' value='" + cartArray[i].product_id + "'>"
+ "<input type = 'hidden' class='sr-only' name='ProductName[]' id='ProductName' value='" +
cartArray[i].name + "'>"
+ "<input type = 'hidden' class='sr-only' name='ProductPrice[]' id='ProductPrice' value='" +
cartArray[i].price + "'>"
+ "<input type = 'hidden' class='sr-only' name='ProductQuantity[]' id='ProductQuantity'
value='" +
cartArray[i].count + "'>"
+ "<input type = 'hidden' class='sr-only' name='TotalOrderedItems' id='TotalOrderedItems'
value='"
+ total_order + "'></div>"
+ "<hr/>" ;
}
$('.show-cart').html(output);
46 | Page
$('.total-cart').html(shoppingCart.totalCart());
$('.total-count').html(shoppingCart.totalCount());
}
// Delete item button
$('.show-cart').on("click", ".delete-item", function(event) {
"use strict";
var name = $(this).data('name');
var product_id = $(this).data('product_id');
shoppingCart.removeItemFromCartAll(product_id);
displayCart();
})
// -1
$('.show-cart').on("click", ".minus-item", function(event) {
"use strict";
var name = $(this).data('name');
var product_id = $(this).data('product_id');
shoppingCart.removeItemFromCart(product_id);
displayCart();
})
// +1
$('.show-cart').on("click", ".plus-item", function(event) {
"use strict";
var name = $(this).data('name');
var product_id = $(this).data('product_id');
shoppingCart.addItemToCart(product_id);
displayCart();
})
// Item count input
$('.show-cart').on("change", ".item-count", function(event) {
47 | Page
"use strict";
var name = $(this).data('name');
var count = Number($(this).val());
var product_id = $(this).data('product_id');
shoppingCart.setCountForItem(product_id, count);
displayCart();
});
displayCart();
// =============================
// Cart toast display
// =============================
$('.show-toast').on("click",function(){
"use strict";
const x = document.getElementById("product-toast");
var item_name = $(this).data('name');
$("#item-name").text(item_name);
x.className = "show";
setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
});
body {
padding-top: 80px;
}
/* product cart design */
.show-cart li {
display: flex;
}
.card {
margin-bottom: 20px;
}
48 | Page
card-img-top {
width: 200px;
height: 200px;
align-self: center;
}
.card-product .img-wrap {
border-radius: 3px 3px 0 0;
overflow: hidden;
position: relative;
height: 220px;
text-align: center;
}
.card-product .img-wrap img {
max-height: 100%;
max-width: 100%;
object-fit: cover;
}
.card-product .info-wrap {
overflow: hidden;
padding: 15px;
border-top: 1px solid #eee;
}
.card-product .bottom-wrap {
padding: 15px;
border-top: 1px solid #eee;
}
.label-rating { margin-right:10px;
color: #333;
display: inline-block;
49 | Page
vertical-align: middle;
}
.card-product .price-old {
color: #999;
}
.fa-2x-cart{
font-size:24px
}
/* shopping cart counter */
.header{background:rgb(0, 178, 255);color:#fff;}
#lblCartCount {
font-size: 12px;
background: #ff0000;
color: #fff;
padding: 0 5px;
vertical-align: top;
margin-left: -10px;
}
.badge {
padding-left: 9px
padding-right: 9px;
-webkit-border-radius: 9px;
-moz-border-radius: 9px;
border-radius: 9px;
}
.label-warning[href],
.badge-warning[href] {
background-color: #c67605;
}
50 | Page
/* shopping cart counter style */
i.fa-shopping-cart {
width:2.2em;
text-align:center;
vertical-align:middle;
}
.fa-shopping-cart {
margin-top: 0.2em;
position: relative;
}
.badge {
font-size: .25em;
display: block;
position: absolute;
top: -.70em;
right: -.70em;
width: 2.5em;
height: 2.4em;
line-height: 2em;
border-radius: 50%;
text-align: center;
color: #fff;
background: rgba(207, 0, 15, 1);
}
/* product zoom on hover */
.zoom, .zoom-sm {
transition: transform .2s;
}
.zoom:hover {
51 | Page
transform: scale(1.05);
}
.zoom-sm:hover {
transform: scale(1.03);
}
/* shopping cart toast */
#product-toast {
visibility: hidden;
max-width: 50px;
height: 50px;
margin: auto;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 2px;
position: fixed;
z-index: 1;
left: 0;right:0;
bottom: 30px;
font-size: 17px;
white-space: nowrap;
}
#product-toast #img{
width: 70px;
height: 50px;
float: left;
padding-top: 16px;
padding-bottom: 16px;
box-sizing: border-box;
background-color: #111;
52 | Page
color: #fff;
}
#product-toast #desc{
color: #fff;
padding: 16px;
overflow: hidden;
white-space: nowrap;
}
#product-toast.show {
visibility: visible;
-webkit-animation: fadein 0.5s, expand 0.5s 0.5s,stay 3s 1s, shrink 0.5s 2s, fadeout 0.5s 2.5s;
animation: fadein 0.5s, expand 0.5s 0.5s,stay 3s 1s, shrink 0.5s 4s, fadeout 0.5s 4.5s;
}
@-webkit-keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
@keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
@-webkit-keyframes expand {
from {min-width: 50px}
to {min-width: 350px}
}
@keyframes expand {
from {min-width: 50px}
to {min-width: 350px}
}
@-webkit-keyframes stay {
53 | Page
from {min-width: 350px}
to {min-width: 350px}
}
@keyframes stay {
from {min-width: 350px}
to {min-width: 350px}
}
@-webkit-keyframes shrink {
from {min-width: 350px;}
to {min-width: 50px;}
}
@keyframes shrink {
from {min-width: 350px;}
to {min-width: 50px;}
}
@-webkit-keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 60px; opacity: 0;}
}
@keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 60px; opacity: 0;}
}
54 | Page
OUTPUT:
55 | Page
3. Use JavaScript for doing client – side validation of the pages implemented in
experiment 1 andexperiment 2.
PROGRAM:
consttop_items_count = document.querySelector('.items-count'),
bottom_items_count = document.querySelector('.bottom-items-count'),
exit = document.querySelector('.exit'),
bucket = document.querySelector('.cart').style;
var items = document.querySelectorAll('.items');
top_items_count.innerHTML = count;
bottom_items_count.innerHTML = count;
function openBucket() {
bucket.visibility = "visible";
bucket.opacity = "1";
bucket.zIndex = "9";
bucket.transition = "all 0.5s";
}
exit.addEventListener('click', () => {
bucket.visibility = "hidden";
bucket.opacity = "0";
bucket.zIndex = "-9";
bucket.transition = "all 0.5s";
});
var food_cart = [];
() => {
if (localStorage.food_cart) {
food_cart = JSON.parse(localStorage.food_cart);
showCart();
}
}
var qty=1;
for (i = 0; i<= items.length - 1; i++) {
56 | Page
var count=0;
items[i].onclick = e => {
count=count+1
var itemName = e.target.dataset.item;
var price = e.target.dataset.price;
addToCart(itemName, price, qty);
top_items_count.innerHTML = count;
bottom_items_count.innerHTML = count;
}
}
function addToCart(itemName, price,qty) {
for (var i in food_cart) {
if (food_cart[i].Product == itemName) {
food_cart[i].Qty += qty;
showCart();
saveCart();
return;
}
}
var itemArray = {
Product: itemName,
Price: price,
Qty: qty
}
food_cart.push(itemArray)
saveCart();
showCart();
}
function saveCart() {
if (window.localStorage) {
57 | Page
localStorage.food_cart = JSON.stringify(food_cart);
}
}
function deleteItem(index) {
food_cart.splice(index, 1);
showCart();
saveCart();
}
function showCart() {
if (food_cart.length == 0) {
var _ul = document.querySelector('#ul');
_ul.innerHTML = "";
return;
}
var _ul = document.querySelector('#ul');
_ul.innerHTML = "";
for (var i in food_cart) {
var item = food_cart[i];
var li = document.createElement("li")
var row = `<span>${item.Product}</span><span onclick='deleteItem(" + i + ")'><i
class='fasfatrash'></i></span><span>${item.Qty}</span><span>${item.Qty *
item.Price}</span>`;
li.innerHTML += row;
var _ul = document.querySelector('#ul');
_ul.appendChild(li);
}
}
58 | Page
OUTPUT:
59 | Page
4. Explore the features of ES6 like arrow functions, callbacks, promises,
async/await. Implementan application for reading the weather information
from openweathermap.org and display the information in the form of a
graph on the web page.
Arrow functions are introduced in ES6, which provides you a more accurate way to write the
functions in JavaScript. They allow us to write smaller function syntax. Arrow functions
make your code more readable and structured.
1. constfunctionName = (arg1, arg2, ?..) => {
2. //body of the function
3. }
There are three parts to an Arrow Function or Lambda Function:
o Parameters: Any function may optionally have the parameters.
o Fat arrow notation/lambda notation: It is the notation for
the arrow (=>).
o Statements: It represents the instruction set of the function.
// function expression
var myfun1 = function show() {
console.log("It is a Function Expression");
}
// Anonymous function
var myfun2 = function () {
console.log("It is an Anonymous Function");
}
//Arrow function
var myfun3 = () => {
console.log("It is an Arrow Function");
};
myfun1();
myfun2();
myfun3();
OUTPUT:
60 | Page
ES6 Promises
A Promise represents something that is eventually fulfilled. A Promise can either be rejected
or resolved based on the operation outcome.
ES6 Promise is the easiest way to work with asynchronous programming in JavaScript.
Asynchronous programming includes the running of processes individually from the main
thread and notifies the main thread when it gets complete. Prior to the Promises, Callbacks
were used to perform asynchronous programming.
Callback
A Callback is a way to handle the function execution after the completion ofthe execution of
another function.
A Callback would be helpful in working with events. In Callback, a functioncan be passed as
a parameter to another function.
Syntax
1. const Promise = new Promise((resolve,reject) => {....});
Example
1. let Promise = new Promise((resolve, reject)=>{
2. let a = 3;
3. if(a==3){
4. resolve('Success');
5. }
6. else{
7. reject('Failed');
8. }
9. })
10. Promise.then((message)=>{
11. console.log("It is then block. The message is: ?+ message)
12. }).catch((message)=>{
13. console.log("It is Catch block. The message is: ?+ message)
14. })
61 | Page
Output
JavaScript Async/Await:
JavaScript is always synchronous and single-threaded that provides the event loops. The event loops
enable us to queue up an activity. This activity will not happen until the loops become available after
the program that queued the action has completed the execution. However, our program contains a
large number of functionalities, which causes our code to be asynchronous. The Async/Await
functionality is one of them. Async/Await is an extension of promises that we get as language
support.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="utf-8">
5. <title>JavaScript Async</title>
6. </head>
7. <body>
8. <h2>JavaScript Async</h2>
9. <p id="main"></p>
10.<script>
11. function myDisplayer(some) {
12. document.getElementById("main").innerHTML = some;
13. }
14.async function myfirstFunction() {
15. return "Hello World!!!";
16. }
17. myfirstFunction().then(
18. function(value) {myDisplayer(value);},
19. function(error) {myDisplayer(error);}
20.);
21. </script>
22.</body>
62 | Page
23. </html>
Output:
After executing the above code, we will get the output shownbelow in the screenshot.
JavaScript Await
JavaScript Await function is used to wait for the promise. It could only be used inside the async
block. It instructs the code to wait until the promise returns aresponse. It only delays the async block.
Await is a simple command that instructs JavaScript to wait for an asynchronous action to complete
before continuing with the feature. It's similar to a "pause until done" keyword. The await keyword is
used to retrieve a value from a function where we will usually be used the then() function. Instead of
calling after the asynchronous function, we'd use await to allocate a variable to the result and then
use the result in the code as we will in the synchronous code.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="utf-8">
5. <title>JavaScript Await</title>
6. </head>
7. <body>
8. <h2>JavaScript Await</h2>
9. <p id="main"></p>
10. <script>
11. async function myDisplay() {
12. let myPromise = new Promise(function(myResolve, myReject) {
63 | Page
13. myResolve("Hello World!!");
14. });
15. document.getElementById("main").innerHTML = await myPro
mise;
16. }
17. myDisplay();
18. </script>
19. </body>
20. </html>
Output:
After executing this code, we will get the output as shown below in
the screenshot:
Implementan application for reading the weather information from openweathermap.org and
display the information in the form of a graph on the web page.
MainPage.html
<!DOCTYPE html>
<html>
<head>
<title>Weather Report</title>
<link rel="icon" href="favicon.png">
<link rel="stylesheet" href="PageStyle.css">
<link href=
'https://fonts.googleapis.com/css?family=Delius Swash Caps'
rel='stylesheet'>
</head>
<body>
64 | Page
<p id="data" class="styleIt"></p>
<script src="JSPage.js"></script>
</body>
</html>
PageStyle.css
p.styleIt
{
background-color: rgb(182, 182, 182);
border: 2px solid rgb(182, 182, 182);
border-radius: 8px;
text-align: center;
box-shadow: 6px 5px 2px rgb(182, 182, 182), 0 0 25px rgb(0, 0, 0), 0 0 5px
rgb(182, 182, 182);
font-family: 'Delius Swash Caps';
}
body{
background:rgb(120, 120, 120);
margin: 0;
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%)
}
JSPage.js
var data =
document.getElementById("data
");
var Latitude;
var Longitude;
var key = "------Put Your Own Key-----";
65 | Page
var url = "http://api.openweathermap.org/data/2.5/weather?";
function getLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
data_of_Lat_Lon.innerHTML="Geolocation is not
supported by this browser. SORRY!";
}
}
function showPosition(position){
Latitude = position.coords.latitude;
Longitude = position.coords.longitude;
getData(Latitude,Longitude);
}
function getData(Lat,Lon){
constreadyToSent =
(url+"lat="+Lat+"&lon="+Lon+"&appid="+key);
fetch(readyToSent)
.then(response=>response.json())
.then(data=>{
console.log(data);
fetchData(data)
})
}
function fetchData(data){
const icon =
"http://openweathermap.org/img/wn/"+data.weather[0].icon+"@2
x.png"
66 | Page
document.getElementById("data").innerHTML =
"<b>The weather report of your Location is
:-</b><br>"+
"<imgsrc="+icon+"><br>"+
"<b>Country :</b>"+data.sys.country+
"<br><b>Local Area Name :</b>"+data.name+
"<br><b>Temp. :</b>"+parseFloat((data.main.temp -
273.15)).toFixed(1)+"℃"+
"<br><b>But You will feel like
:</b>"+parseFloat((data.main.feels_like -
273.15)).toFixed(1)+"℃"+
"<br><b>Min. Temp.
:</b>"+parseFloat((data.main.temp_min -
273.15)).toFixed(1)+"℃"+
"<br><b>Max. Temp.
:</b>"+parseFloat((data.main.temp_max -
273.15)).toFixed(1)+"℃"+
"<br><b>Pressure :</b>"+data.main.pressure+"hPa"+
"<br><b>Humidity :</b>"+data.main.humidity+"%"+
"<br><b>Weather :</b>"+data.weather[0].description+
"<br>"
}
getLocation();
showPosition();
getData();
67 | Page
OUTPUT:
68 | Page
5. Develop a java stand alone application that connects with the database
(Oracle / mySql) and perform the CRUD operation on the database tables.
PROGRAM:
CREATING A USER ID USING JAVA:
public class User {
private int id;
private String firstName;
private String lastName;
private String email;
@Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
'}';
}
}
69 | Page
CONNECTING DATABASE TO JAVA APPLICATION:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
70 | Page
ResultSetresultSet = statement.executeQuery()) {
while (resultSet.next()) {
int id = resultSet.getInt("id");
String firstName = resultSet.getString("first_name");
String lastName = resultSet.getString("last_name");
String email = resultSet.getString("email");
return users;
}
statement.setString(1, user.getFirstName());
statement.setString(2, user.getLastName());
statement.setString(3, user.getEmail());
statement.executeUpdate();
}
}
71 | Page
String query = "UPDATE users SET first_name= ?, last_name = ?, email = ? WHERE id
= ?";
statement.setString(1, user.getFirstName());
statement.setString(2, user.getLastName());
statement.setString(3, user.
72 | Page
6.Create an xml for the bookstore. Validate the same using both DTD and
XSD
PROGRAM:
< booksinfor.dtd >
<!ELEMENT books (book+)>
<!ELEMENT book (title,author,ISBN,publisher,edition,price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT ISBN (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT edition (#PCDATA)>
<!ELEMENT price (#PCDATA)>
73 | Page
<publisher>Pearson</publisher>
<edition>4nd edition</edition>
<price>Rs.350</price>
</book>
<book>
<title>Frontiers of Electronic commerce</title>
<author>Kalakata</author>
<ISBN>978-81-265-1173-0</ISBN>
<publisher>Pearson</publisher>
<edition>1st edition</edition>
<price>Rs.350</price>
</book>
<book>
<title>Java Programming with CORBA</title>
<author>G.Brose</author>
<ISBN>978-81-265-1173-0</ISBN>
<publisher>Wiley Dreamtech</publisher>
<edition>2nd edition</edition>
<price>Rs.250</price>
</book>
<book>
<title>The Unified Modelling language User Guide</title>
<author>GradyBooch,JamesRumbaugh,IvarJacabson</author>
<ISBN>81-7758-372-7</ISBN>
<publisher>Perarson Education</publisher>
<edition>2nd edition</edition>
<price>Rs.400</price>
</book>
<book>
<title>Data mining - Concepts and techniques </title>
74 | Page
<author> Jiawei HAn and Kamber</author>
<ISBN>978-81-312-0538-8</ISBN>
<publisher>Pearson</publisher>
<edition>1st edition</edition>
<price>Rs.550</price>
</book>
</books>
75 | Page
<td><xsl:value-of select="publisher"/></td>
<td><xsl:value-of select="edition"/></td>
<td><xsl:value-of select="price"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
OUTPUT:
76 | Page
7. Design a controller with servlet that provides the interaction with
application developed inexperiment 1 and the database created in
experiment 5.
PROGRAM:
Mysql database
Procedure:
Reg.html:
<html>
<head>
<title> validation </title>
</head>
<body bgcolor="magenta">
<form action="Register.jsp" method="post">
lOMoARcPSD|16678339
<h1 align="center">REGISTRATION FORM</h1>
<table border="0">
<tr>
<td>Name:</td>
<td><input type="text" name="t1" min length="6"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="t2"></td>
</tr>
<tr>
<td>Phone number:</td>
<td><input type="text" name="t3"></td>
</tr>
<tr>
<td>E-mail id:</td>
77 | Page
<td><input type="text" name="t4"></td>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
<td><input type="reset" value="cancel"></td>
</tr>
</table>
</form>
</body>
</html>
Register.jsp:
<%@ page language="java" import="java.sql.*,javax.servlet.*" %>
<html>
<form >
<%
String v1,v2,v3,v4,str;
v1=request.getParameter("t1");
v2=request.getParameter("t2");
v3=request.getParameter("t3");
v4=request.getParameter("t4");
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:oradsn","system","ravindra");
Statement st=cn.createStatement();
st.executeUpdate("insert into register values('"+v1+"','"+v2+"',"+v3+",'"+v4+"')");
if(cn!=null)
{
%>
</form>
Registration Successful
78 | Page
<%
}
else
{
out.println("Registration failed");
}
st.close();
cn.close();
}catch(Exception e) { out.println(" Registration failed");
%>
<P><a href = "reg.html" target =f2 ><B> Back<B></a>
<%
}
%>
</body></html>
Execution:
Create a table with name register with name (varchar2 (10)), password (varchar2 (10)),
Phone(number (10)) ,Email-ID (varchar2(10)).
Create the Data source name.
Start->settings->control panel->Administrative Tools->Data Sources.
Under SystemDSN add Microsoft ODBC for Oracle.
Set Data Source name to oradsn.
Output:1
79 | Page
OUTPUT:2
80 | Page
package com.journaldev.servlet.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "admin";
private final String password = "password";
protected void doPost(HttpServletRequest request,
81 | Page
HttpServletResponse response) throws ServletException, IOException {
// get request parameters for userID and password
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if(userID.equals(user) &&password.equals(pwd)){
HttpSession session = request.getSession();
session.setAttribute("user", "Pankaj");
//setting session to expiry in 30 mins
session.setMaxInactiveInterval(30*60);
Cookie userName = new Cookie("user", user);
userName.setMaxAge(30*60);
response.addCookie(userName);
response.sendRedirect("LoginSuccess.jsp");
}else{
RequestDispatcherrd =
getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is
wrong.</font>");
rd.include(request, response);
}
}
}
82 | Page
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<%
//allow access only if session exists
String user = null;
if(session.getAttribute("user") == null){
response.sendRedirect("login.html");
}else user = (String) session.getAttribute("user");
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();}
}
%>
<h3>Hi <%=userName %>, Login successful. Your Session ID=<%=sessionID %></h3>
<br>
User=<%=user %>
<br>
<a href="CheckoutPage.jsp">Checkout Page</a>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>
83 | Page
When a JSP resource is used, container automatically creates a session for it, so we can’t
check if session is null to make sure if user has come through login page, so we are using
session attribute to validate request. CheckoutPage.jsp is another page and it’s code is given
below.
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<%
//allow access only if session exists
if(session.getAttribute("user") == null){
response.sendRedirect("login.html");
}
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
%>
<h3>Hi <%=userName %>, do the checkout.</h3>
<br>
84 | Page
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>
85 | Page
break;
}
}
}
//invalidate the session if exists
HttpSession session = request.getSession(false);
System.out.println("User="+session.getAttribute("user"));
if(session != null){
session.invalidate();
}
response.sendRedirect("login.html");
}
}
OUTPUT:
9. Create a custom server using http module and explore the other modules
of Node JS like OS,path, event.
The http.createServer() method includes request and response parameters which is supplied
by Node.js. The request object can be used to get information about the current HTTP request
86 | Page
e.g., url, request header, and data. The response object can be used to send a response for a
current HTTP request.
The following example demonstrates handling HTTP request and response in Node.js.
var http = require('http'); // Import Node.js core module
var server = http.createServer(function (req, res) { //create web
server
if (req.url == '/') { //check the URL of the current request
// set response header
res.writeHead(200, { 'Content-Type': 'text/html' });
// set response content
res.write('<html><body><p>This is home
Page.</p></body></html>');
res.end();
}
else if (req.url == "/student") {
}
else if (req.url == "/admin") {
87 | Page
res.end('Invalid Request!');
});
server.listen(5000); //6 - listen for any incoming requests
console.log('Node.js web server at port 5000 is running..')
10. Develop an express web application that can interact with REST API to
perform 14 CRUDoperations on student data. (Use Postman)
#1) Installations.
88 | Page
#2) Create new Node.js Project with Express.js
#3) CRUD Operations and HTTP methods.
#4) Testing API with Postman.
Installation Required
● Node.js Or NPM (Node Package Manager)
● VS Code (Optional) — A code editor.
To check whether the Node.js is already installed on your computer,
open your terminal or CMD and run node -v command. If you see
your Node.js version means it's installed.
Otherwise go to these links and install:
→ Click here to download and install Node.js (You should choose LTS
version).
→ Click here to download VS Code
Express application generator:
To quickly create an application skeleton. You may use this
application generator tool (`express-generator`). The application
generator uses npx command (available in Node.js newer versions).
→ Click here to know more about Express application generator.
We will not use express-generator in this article, instead we will create
everything by ourself to avoid extra files generated from generator
and to understand in depth.
#2) Create New Project (using Node.js with Express.js)
Create a new folder (at the place you want to keep your project).
Name that folder: node-ex-api
Create two files inside node-ex-api folder:
→ package.json file.
→ server.js file.
Open up and update your node-ex-api/package.json file with below
code:
{
89 | Page
"name": "node-ex-api",
"version": "1.0.0",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.17.1"
}
}
Open up and update your node-ex-api/server.js file with below code:
const http = require('http');
const express = require('express');
const app = express();
app.use(express.json());
// default URL to API
app.use('/', function(req, res) {
res.send('node-ex-api works :-)');
});
const server = http.createServer(app);
const port = 3000;
server.listen(port);
console.debug('Server listening on port ' + port);
After creating above two files, open your terminal in the "node-exapi" folder and run
this command:
npm install
90 | Page
After dependency installation this will create "node_modules" folder at the root of the
"node-ex-api" folder.
Run Project
We have just created a Node-Express Project Let’s start a server. To start a
server run this command:
To test this API — Open your web browser and enter this
URL → localhost:3000
The localhost:3000 is calling default Server Path. Which returns simple string
“node-ex-api works :-)”
91 | Page
CRUD Operations and HTTP methods.
92 | Page
DELETE http methods in web browser. To test those methods we
use Postman or you may use another http utility to call APIs.
Here we use Postman. So before start click here and install Postman.
Now, run npm start if your server is not running.
After Postman installation skip start window (if comes), then login
with Google or email/password (whichever you prefer) and finally you
must see this screen:
OUTPUT:
93 | Page
11.For the above application create authorized end points using JWT (JSON
Web Token).
PROGRAM:
Create API endpoints Our default endpoint returns string — we see that above.
Now we’ll create another API endpoint, that is another URL which returns some
useful data.
Before proceed, let’s do some more exercise:
→ Create a folder inside the project root with name "routes".
→ Then create a file inside this "routes" folder with name "items.js".
Next, Open up and update your node-ex-api/routes/items.js file with below
code:
// import required essentials const express = require('express');
// create new router
const router = express.Router();
// create a JSON data array
let data = [
{ id: 1, title: 'Create a project', order: 1, completed:
true, createdOn: new Date() },
{ id: 2, title: 'Take a cofféé', order: 2, completed:
true, createdOn: new Date() },
{ id: 3, title: 'Write new article', order: 3, completed:
true, createdOn: new Date() },
{ id: 4, title: 'Walk toward home', order: 4, completed:
false, createdOn: new Date() },
{ id: 5, title: 'Have some dinner', order: 5, completed:
false, createdOn: new Date() },
];
// this end-point of an API returns JSON data array
router.get('/', function (req, res) {
94 | Page
res.status(200).json(data);
});
// this end-point returns an object from a data array find by id
// we get `id` from URL end-points
router.get('/:id', function (req, res) {
// find an object from `data` array match by `id`
let found = data.find(function (item) {
return item.id === parseInt(req.params.id);
});
// if object found return an object else return 404 not-found
if (found) {
res.status(200).json(found);
} else {
res.sendStatus(404);
}
});
module.exports = router;
See below ↓↓
95 | Page
Register API endpoints
Let’s register it in the "server.js" file to make use of new endpoints.
Do not forget to install CORS.
Open your terminal in the "node-ex-api" folder and run this command:
npm install cors
Now, open up your node-ex-api/server.js file and modify with below code:
// import required essentials
const http = require('http');
const express = require('express');
var cors = require('cors');// import `items` from `routes` folder
constitemsRouter = require('./routes/items');
// create new app
const app = express();
app.use(express.json());
// use it before all route definitions
// allowing below URL to access these APIs end-points
// you can replace this URL(http://localhost:8100) with your
// application URL from where you are calling these APIs app.use(cors({origin:
'http://localhost:8100'}));
/* this '/items' URL will have two end-points:
96 | Page
→ localhost:3000/items/ (this returns array of objects)
→ localhost:3000/items/:id (this returns single object) */ app.use('/items',
itemsRouter);
// default URL to API
app.use('/', function(req, res) { res.send('node-ex-api works :-)'); });
const server = http.createServer(app); ‘
const port = 3000;
server.listen(port); console.debug('Server listening on port ' + port);
See below ↓↓
97 | Page
12.Create a react application for the student management system having
registration, login, contact, about pages and implement routing to navigate
through these pages.
Create the project folder containing two sub-folders named client and server.
mkdir auth-system
cd auth-system
mkdir client server
Navigate into the server folder and create a package.json file.
cd server &npminit -y
Install Express.js, CORS, and Nodemon.
npm install express corsnodemon
Express.js is a fast, minimalist framework that provides several features for
building web applications in Node.js. CORS is a Node.js package that allows
communication between different domains. Nodemon is a Node.js tool that
automatically restarts the server after detecting file changes.
Create an index.js file - the entry point to the web server.
touch index.js
Set up a simple Node.js server as below:
const express = require("express");
constcors = require("cors");
const app = express();
const PORT = 4000;
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());
app.get("/api", (req, res) => { res.json({ message: "Hello world" }); });
app.listen(PORT, () => { console.log(`Server listening on ${PORT}`); });
Building the app user interface
98 | Page
In this section,we'll build the user interface for the application allowing users to
register and sign in to an application. Users can create an account, log in, and
perform 2FA via SMS before they are authorised to view the dashboard.
Create a new React.js project within the client folder.
cd client
npx create-react-app ./
Delete the redundant files such as the logo and the test files from the React app,
and update the App.js file to display Hello World as below. function App() {
return (
<div>
<p>Hello World!</p>
</div>); }
export default App;
Navigate into the src/index.css file and copy the code below. It contains all the
CSS required for styling this project.
@import url("https://fonts.googleapis.com/css2?
family=Space+Grotesk:wght@300;400;500;600;700&display=swap");
* { box-sizing: border-box;
margin: 0;
padding: 0;
font-family: "Space Grotesk", sans-serif; }
input {
height: 45px;
padding: 10px 15px;
margin-bottom: 15px; }
button {
width: 200px;
outline: none;
border: none;
padding: 15px;
cursor: pointer;
font-size: 16px; }
.login__container,
.signup__container,
.verify,
.dashboard {
width: 100%;
min-height: 100vh;
padding: 50px 70px;
display: flex; flex-direction: column; align-items: center; justify-content: center;
99 | Page
.login__form,
.verify__form,
.signup__form {
width: 100%;
display: flex;
flex-direction: column;
}
.loginBtn,
.signupBtn,
.codeBtn {
background-color: green;
color: #fff;
margin-bottom: 15px;
}
.signOutBtn {
background-color: #c21010;
color: #fff;
}
.link {
cursor: pointer;
color: rgb(39, 147, 39);
}
.code {
width: 50%;
text-align: center;
}
.verify__form {
align-items: center;
}
@media screen and (max-width: 800px) {
.login__container,
.signup__container,
.verify {
padding: 30px;
}
}
Install React Router - a JavaScript library that enables us to
navigate between pages in a React application.
npm install react-router-dom
Create a components folder within the React app containing
the Signup.js, Login.js, PhoneVerify.js and Dashboard.js files.
mkdir components
cd components
100 | Page
touch Signup.js Login.js PhoneVerify.js Dashboard.js
Update the App.js file to render the newly created
components on different routes via React Router.
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Login from "./components/Login";
import Signup from "./components/Signup";
import Dashboard from "./components/Dashboard";
import PhoneVerify from "./components/PhoneVerify";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path='/' element={<Login />} />
<Route path='/register' element={<Signup />} />
<Route path='/dashboard' element={<Dashboard />} />
<Route path='phone/verify' element={<PhoneVerify />} />
</Routes>
</BrowserRouter>
);
}
export default App;
The Login page
Copy the code below into the Login.js file. It accepts the email
and password from the user.
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const navigate = useNavigate();
consthandleSubmit = (e) => {
e.preventDefault();
console.log({ email, password });
setPassword("");
setEmail("");
};
constgotoSignUpPage = () => navigate("/register");cd components
touch Signup.js Login.js PhoneVerify.js Dashboard.js
Update the App.js file to render the newly created
components on different routes via React Router.
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Login from "./components/Login";
import Signup from "./components/Signup";
101 | Page
import Dashboard from "./components/Dashboard";
import PhoneVerify from "./components/PhoneVerify";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path='/' element={<Login />} />
<Route path='/register' element={<Signup />} />
<Route path='/dashboard' element={<Dashboard />} />
<Route path='phone/verify' element={<PhoneVerify />} />
</Routes>
</BrowserRouter>
);
}
export default App;
The Login page
Copy the code below into the Login.js file. It accepts the email
and password from the user.
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const navigate = useNavigate();
consthandleSubmit = (e) => {
e.preventDefault();
console.log({ email, password });
setPassword("");
setEmail("");
};
constgotoSignUpPage = () => navigate("/register");
return (
<div className='login__container'>
<h2>Login </h2>
<form className='login__form' onSubmit={handleSubmit}>
<label htmlFor='email'>Email</label>
<input
type='text'
id='email'
name='email'
value={email}
required
onChange={(e) =>setEmail(e.target.value)}
102 | Page
/>
<label htmlFor='password'>Password</label>
<input
type='password'
name='password'
id='password'
minLength={8}
required
value={password}
onChange={(e) =>setPassword(e.target.value)}
/>
<button className='loginBtn'>SIGN IN</button>
<p>
Don't have an account?{" "}
<span className='link' onClick={gotoSignUpPage}>
Sign up
</span>
</p>
</form>
</div>
);
};
export default Login;
104 | Page
type='password'
name='password'
id='password'
minLength={8}
required
value={password}
onChange={(e) =>setPassword(e.target.value)}
/>
<button className='signupBtn'>SIGN UP</button>
<p>
Already have an account?{" "}
<span className='link' onClick={gotoLoginPage}>
Login
</span>
</p>
</form>
</div>
);
};
105 | Page
//*** GET SAVED ITEMS FROM LOCAL STORAGE ***//
let savedSearchArray =
JSON.parse(localStorage.getItem('savedSearchArray'));
if (!savedSearchArray) {
savedSearchArray = [
'Columbus',
'Bend',
'Los Angeles',
'San Francisco'
'Savannah',
'New York',
'Nashville'
];
}
// Define Global Date Variables
// Moment.js
let time = document.querySelector('#time');
time.textContent = moment().format('h:mm a');
let today = document.querySelector('#today');
today.textContent = moment().format('MMM D');
let tomorrow = document.querySelector('#date_1');
tomorrow.textContent = moment().add(1, 'days').format('ddd');
let tomorrow2 = document.querySelector('#date_2');
tomorrow2.textContent = moment().add(2, 'days').format('ddd');
let tomorrow3 = document.querySelector('#date_3');
tomorrow3.textContent = moment().add(3, 'days').format('ddd');
let tomorrow4 = document.querySelector('#date_4');
tomorrow4.textContent = moment().add(4, 'days').format('ddd');
let tomorrow5 = document.querySelector('#date_5');
tomorrow5.textContent = moment().add(5, 'days').format('ddd');
// Define variables for getCurrent function
constsearchBtnEl = document.querySelector('#search-btn');
constsearchInputEl = document.querySelector('#search-input');
// Define getCurrent function to access current weather conditions
function getCurrent(searchInputEl) {
// Current Weather Data API call
constcurrentWeatherUrl =
'https://api.openweathermap.org/data/2.5/weather?q=' + searchInputEl +
'&units=imperial&appid=c6a9bf78cf3b504fe7e8382ca53765c4';
fetch(currentWeatherUrl).then(function (response) {
if (response.ok) {
response.json().then(function (data) {
106 | Page
console.log(data)
// Append data from API to DOM
constcityName = document.querySelector('#city-name');
cityName.textContent = data.name;
const icon = document.querySelector('#current-icon');
consticonCall = data.weather[0].icon;
icon.setAttribute('src', 'http://openweathermap.org/img/wn/'
+iconCall+ '.png');
const temp = document.querySelector('#current-temp');
temp.innerHTML = Math.round(data.main.temp) + `º`;
const description = document.querySelector('#desc');
description.textContent = data.weather[0].main;
const humidity = document.querySelector('#current-humid');
humidity.innerHTML = 'Humidity: ' + data.main.humidity +
` %`;
constwindSpeed = document.querySelector('#current_wind');
windSpeed.textContent = 'Wind Speed: ' + data.wind.speed + '
mph';
//call function to render 5 day forecast in this function for access to
latitude and longitude from city search in current weather function
getForecast(data.coord.lat, data.coord.lon);
//access uv index from onecall used for 5 day forecast
})
}
})
};
//define function to get 5 day forecast //access lat and lon from previous
function
//use one call API instead of 5 day forecast //better accessibility to needed
information
function getForecast(latitude, longitude) {
constforecastUrl = 'https://api.openweathermap.org/data/2.5/onecall?lat='
+ latitude + '&lon=' + longitude +
'&units=imperial&exclude=hourly,minutely&appid=c6a9bf78cf3b504fe7e8
382ca53765c4';
fetch(forecastUrl).then(function (response) {
if (response.ok) {
response.json().then(function (data) {
console.log(data)
//append uv data to current conditions div
constuvIndex = document.querySelector('#current_uv');
uvIndex.textContent = 'UV Index: ' + data.current.uvi;
// Render icons for each day in forecast
107 | Page
// Note: Must use <img> tag in html to use .setAttribute method to
set the imgsrc
const icon1 = document.querySelector('#icon1');
const icon1Call = data.daily[1].weather[0].icon;
icon1.setAttribute('src', 'http://openweathermap.org/img/wn/'
+icon1Call+ '@2x.png');
const icon2 = document.querySelector('#icon2');
const icon2Call = data.daily[2].weather[0].icon;
icon2.setAttribute('src', 'http://openweathermap.org/img/wn/'
+icon2Call+ '@2x.png');
const icon3 = document.querySelector('#icon3');
const icon3Call = data.daily[3].weather[0].icon;
icon3.setAttribute('src', 'http://openweathermap.org/img/wn/'
+icon3Call+ '@2x.png');
const icon4 = document.querySelector('#icon4');
const icon4Call = data.daily[4].weather[0].icon;
icon4.setAttribute('src', 'http://openweathermap.org/img/wn/'
+icon4Call+ '@2x.png');
const icon5 = document.querySelector('#icon5');
const icon5Call = data.daily[5].weather[0].icon;
icon5.setAttribute('src', 'http://openweathermap.org/img/wn/'
+icon5Call+ '@2x.png');
//description forecast
//TODO: for loop
const desc1 = document.querySelector('#desc_1');
desc1.innerHTML = (data.daily[1].weather[0].main);
const desc2 = document.querySelector('#desc_2');
desc2.innerHTML = (data.daily[2].weather[0].main);
const desc3 = document.querySelector('#desc_3');
desc3.innerHTML = (data.daily[3].weather[0].main);
const desc4 = document.querySelector('#desc_4');
desc4.innerHTML = (data.daily[4].weather[0].main);
const desc5 = document.querySelector('#desc_5');
desc5.innerHTML = (data.daily[5].weather[0].main);
//temp forecast
//TODO for loop
// for (i = 0; i<forecast.length; i++)
const temp1 = document.querySelector('#temp_1');
temp1.innerHTML = Math.round(data.daily[1].temp.day) +
`º`;
const temp2 = document.querySelector('#temp_2');
temp2.innerHTML = Math.round(data.daily[2].temp.day) +
`º`;
108 | Page
const temp3 = document.querySelector('#temp_3');
temp3.innerHTML = Math.round(data.daily[3].temp.day) +
`º`;
const temp4 = document.querySelector('#temp_4');
temp4.innerHTML = Math.round(data.daily[4].temp.day) +
`º`;
const temp5 = document.querySelector('#temp_5');
temp5.innerHTML = Math.round(data.daily[5].temp.day) +
`º`;
//humidity forecast
//TODO for loop
// for (i = 0; i<forecast.length; i++)
const humid1 = document.querySelector('#humid_1');
humid1.innerHTML = (data.daily[1].humidity) + `%`;
const humid2 = document.querySelector('#humid_2');
humid2.innerHTML = (data.daily[2].humidity) + `%`;
const humid3 = document.querySelector('#humid_3');
humid3.innerHTML = (data.daily[3].humidity) + `%`;
const humid4 = document.querySelector('#humid_4');
humid4.innerHTML = (data.daily[4].humidity) + `%`;
const humid5 = document.querySelector('#humid_5');
humid5.innerHTML = (data.daily[5].humidity) + `%`;
})
}
})
};
//select each search history list item
constsearchHistCon = document.querySelector('#search-history-list')
constsearchedItemEl = searchHistCon.querySelectorAll('li.search-historyitem');
console.log(searchedItemEl);
//define function to render search history
function renderSearchHistory() {
//clear previous selection before appending
for (i = 0; i<savedSearchArray.length; i++) {
constnewSearchedItem = document.createElement('li');
newSearchedItem.classList.add('search-history-item');
newSearchedItem.textContent = savedSearchArray[i];
newSearchedItem.addEventListener('click', function (event) {
let newUserInput = event.target.innerText;
getCurrent(newUserInput);
})
if (newSearchedItem.textContent !== "") {
searchHistCon.prepend(newSearchedItem);
109 | Page
}
}
}
//add event listener to search button
searchBtnEl.addEventListener('click', function (event) {
event.preventDefault();
//use event to access user input
console.log(event);
let userInput= searchInputEl.value;
getCurrent(userInput);
//TODO: if statement to check edge cases of misspelled cities, etc
savedSearchArray.push(userInput);
//call function to render search history within this function for access to
needed variables
renderSearchHistory();
localStorage.setItem('savedSearchArray',
JSON.stringify(savedSearchArray));
});
constsearchHistoryMenuLi = document.querySelector('#search-hist-menuli');
searchHistoryMenuLi.addEventListener('click', renderSearchHistory());
getCurrent('Columbus');
Whether.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.cs
s" rel="stylesheet" integrity="sha384-
EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65Vohhpuu
COmLASjC" crossorigin="anonymous">
<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"
integrity="sha384-
50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhn
dOJK28anvf" crossorigin="anonymous" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?
family=Josefin+Sans:ital,wght@0,100;0,200;0,300;0,400;0,500;1,100;1,200
;1,300;1,400&family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;
110 | Page
0,600;0,700;0,800;0,900;1,100;1,200;1,300&family=Noto+Sans:ital,wght@
0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300&
family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,80
0;0,900;1,100;1,200;1,300&family=Roboto:ital,wght@0,100;0,300;0,400;0,
500;0,700;0,900;1,100;1,300;1,400&family=Rubik+80s+Fade&family=Sour
ce+Sans+Pro:wght@300&display=swap" rel="stylesheet">
<link rel="stylesheet" href="assets/css/reset.css" />
<link rel="stylesheet" href="assets/css/style.css" />
<link rel="stylesheet" href="assets/css/responsive.css" />
<title>Current Weather</title>
</head>
<body>
<div class="navbar">
<!-- Dropdown menu -->
<nav class="btn-group dropend">
<button type="button" class="btn dropdown-toggle" data-bstoggle="dropdown"
aria-expanded="false"></button>
<ul class="dropdown-menu" id="popout-menu">
<li class="nav-item dropdown-item" id="search-boxtxt">Search
<form class="active search-form " aria-current="page"
href="#">
<div class="input-group">
<input type="text" class="input" id="search-input">
<div class="input-group-div" id="search-btn-group">
<button class="btnbtn-default" id="search-btn"
type="submit">
<i class="fas fa-search" id="search-icon"></i>
</button>
</div>
</div>
</form>
</li>
<li id="search-hist-menu-li" class="nav-item dropdown-item">
History
<ul id="search-history-list">
<!--append search history in script-->
</ul>
</li>
<!--<li class="nav-item dropdown-item"> Starred
<ul id="favorites-list"> -->
<!--append search history in script-->
<!--</ul>
</li> -->
111 | Page
</ul>
</nav>
</div>
<main class="d-flex flex-column gy-2">
<!-- Current Weather Display -->
<div class="container" id="current-conditions">
<div class="d-flex flex-column align-items-center">
<div class="" id="time"></div>
<div class="" id="today"></div>
<div class="display-1" id="current-temp"></div>
<div class="current-icon-wrapper">
<div class="lead text-muted" id="desc"></div>
<img class="display-1" id="current-icon"/>
</div>
</div>
<div class="hidden">
<div class="" id="current-humid"></div>
<div class="" id="current_wind">Wind Speed: </div>
<div class="" id="current_uv">UV Index: </div>
</div>
</div>
<!-- Forecast Card Container -->
<div class="forecast-content-wrapper container d-flex flex-row
justify-content-center" id="week-forecast">
<div class="forecast-card">
<div class="day" id="date_1"></div>
<div class="temperature" id="temp_1"></div>
<div class="description" id="desc_1"></div>
<img class="weather-icon" alt="weather-icon"
id="icon1"></img>
<div class="humidity" id="humid_1"></div>
</div>
<div class="forecast-card">
<div class="day" id="date_2"></div>
<div class="temperature" id="temp_2"></div>
<div class="description" id="desc_2"></div>
<img class="weather-icon" alt="weather-icon"
id="icon2"></img>
<div class="humidity" id="humid_2"></div>
</div>
<div class="forecast-card">
<div class="day" id="date_3"></div>
<div class="temperature" id="temp_3"></div>
112 | Page
<div class="description" id="desc_3"></div>
<img class="weather-icon" alt="weather-icon"
id="icon3"></img>
<div class="humidity" id="humid_3"></div>
</div>
<div class="forecast-card">
<div class="day" id="date_4"></div>
<div class="temperature" id="temp_4"></div>
<div class="description" id="desc_4"></div>
<img class="weather-icon" alt="weather-icon"
id="icon4"></img>
<div class="humidity" id="humid_4"></div>
</div>
<div class="forecast-card">
<div class="day" id="date_5"></div>
<div class="temperature" id="temp_5"></div>
<div class="description" id="desc_5"></div>
<img class="weather-icon" alt="weather-icon"
id="icon5"></img>
<div class="humidity" id="humid_5"></div>
</div>
</div>
<div class="text-muted container" id="city-name">Search a
City</div>
</main>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.m
in.js" integrity="sha384-
MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcX
n/tWtIaxVXM" crossorigin="anonymous"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></scri
pt>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js
"></script>
<script src="assets/script.js"></script>
</body>
</html>
113 | Page
14.Create a TODO application in react with necessary components and
deploy it into github.
<!
DOCTYPE
html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See
https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
114 | Page
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Todo List</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
App.js file:-
import
React
from
"react"
;
import "./App.css";
import { Button, Card, Form } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
function Todo({ todo, index, markTodo, removeTodo }) {
return (
<div
className="todo"
>
<span style={{ textDecoration: todo.isDone ? "line-through" :
"" }}>{todo.text}</span>
<div>
<Button variant="outline-success" onClick={() =>
markTodo(index)}>✓</Button>{' '}
<Button variant="outline-danger" onClick={() =>
removeTodo(index)}>✕</Button>
</div>
</div>
115 | Page
);
}
function FormTodo({ addTodo }) {
const [value, setValue] = React.useState("");
consthandleSubmit = e => {
e.preventDefault();
if (!value) return;
addTodo(value);
setValue("");
};
return (
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label><b>Add Todo</b></Form.Label>
<Form.Control type="text" className="input" value={value} onChange={e =>
setValue(e.target.value)} placeholder="Add new todo" />
</Form.Group>
<Button variant="primary mb-3" type="submit">
Submit
</Button>
</Form>
);
}
function App() {
const [todos, setTodos] = React.useState([
{
text: "This is a sampetodo",
isDone: false
}
]);
constaddTodo = text => {
constnewTodos = [...todos, { text }];
setTodos(newTodos);
};
constmarkTodo = index => {
constnewTodos = [...todos];
newTodos[index].isDone = true;
setTodos(newTodos);
};
constremoveTodo = index => {
constnewTodos = [...todos];
newTodos.splice(index, 1);
setTodos(newTodos);
116 | Page
};
return (
<div className="app">
<div className="container">
<h1 className="text-center mb-4">Todo List</h1>
<FormTodoaddTodo={addTodo} />
<div>
{todos.map((todo, index) => (
<Card>
<Card.Body>
<Todo
key={index}
index={index}
todo={todo}
markTodo={markTodo}
removeTodo={removeTodo}
/>
</Card.Body>
</Card>
))}
</div>
</div>
</div>
);
}
export default App;
Prerequisites
1. Download Git and go through the default installation process.
2. An adequate version of NodeJS and npm should be installed. Here
is the command to check the installation and version.
$ node --version
$ npm --version
3. An adequate version of create-react-app is installed. Here is the
command to check the installation and version.
$ create-react-app --version
If it’s not installed then use the command below to install it globally.
$ npm install -g create-react-app
4. A GitHub account.
Now The Real Fun Begins (Procedure)
1. Firstly create a React application in your system using the
command given below. We are giving the name “react-deploy” to this
application. This is the app you will deploy to GitHub Pages. This
process will create a new folder named “react-deploy” in your
directory.
$ create-react-app react-deploy
2. Now enter your new application and run the following command to
start the application. You will see your application is running on a
local development server http://localhost:3000.
#change directory
$ cd react-deploy
#run application in the development environment
$ npm start
118 | Page
3. After checking that your application runs perfectly without any
error on a local server, create a new repository on GitHub. We are
giving this name “my-app” which is different from the application
name you have created in the previous step. However, you can also
choose the same name i.e. “react-deploy” for your GitHub repository
name. It’s totally up to you.
119 | Page
Next, if you are using the Router from react-router-dom then you
need to change the Browser router tags to
//...
BrowserRouterbasename={process.env.PUBLIC_URL}
//...
6. In this step create a git repository in the app’s folder and add the
GitHub repository as a “remote” in your local git repository. This will
make it so the gh-pages package knows where you want it to deploy
your app in step 7. It will also make it so git knows where you want it
to push your source code (i.e. the commits on your master branch) in
step 8.
#create a new git repository
$ git init
#add remote repository
$ git remote add origin https://github.com/anuupadhyay/my-app.git
7. Now here is the magic. Follow the command below and generate a
production build of your app, to deploy your code on GitHub pages.
#deploy application
$ npm run deploy
That’s it. Your React application is published on GitHub pages and if
you want to verify it just go to the settings tab of your application in
your Github repository and scroll down. You will see something like
below…
120 | Page
In our case, the app is accessible
at: https://anuupadhyay.github.io/my-app/
8. At this point, if you will explore the GitHub repository you will
notice that the master branch did not exist, a gh-pages branch did
exist. It means the latter contained the built app code, as opposed to
the app’s source code. So to create a default master branch and
push your source code to it run the command given below…
#add all changed file paths to staged changes
$ git add .
#commit all staged changes
$ git commit -m "Create a React app and publish it to GitHub Pages"
#pushed local repository to remote repository on GitHub
$ git push origin master
After this last step once again explores the GitHub repository. You will
notice that a master branch now existed, and it contained the app’s
source code. You will see something like below in your GitHub
repository.
121 | Page