JavaScript Indepth Complete Notes (1)
JavaScript Indepth Complete Notes (1)
- JIT [Just-in-Time] is the process where JavaScript is loaded into browser and compiled in browser.
- AOT [Ahead-of-Time] is the process where JavaScript is compiled and processed at application level.
Evolution of JavaScript
Where to implement?
- HTML Client Side
- Node JS server side
- MongoDB database
- Flash, 3DS Max animations
2
- WebPack
- Parcel
- https://nodejs.org/en/
- Download and Install 18x version
C:\>node -v
C:\>npm -v
Note: Make sure that your PC is have Node version > 14 , NPM > 6
https://code.visualstudio.com/
D:\JavaScript-Project
3
a) public : It is used to keep all static resources
[html, images, text, pdf, docx, ppt, mp4,..]
5. Install ESLint configuration, It is used to verify the code and report the issues in code. [ issues related to
coding standards]
4
FAQ: What are the issues with JavaScript?
Ans:
- JavaScript is not a strongly typed language.
var age = 23;
age = "John"; // valid
age = true; // valid
a) Inline
b) Embedded
c) External File
Inline JavaScript:
- In this technique JavaScript functions are directly written in HTML elements start tag.
- It is faster in responding.
- It is not good for reusability.
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>JavaScript - ES6</h2>
<button onclick="window.print()">Print</button>
</body>
</html>
5
Embedded
---------------
- JavaScript functions are kept in a <script> container and can be accessed from any element.
- You can reuse the funcitons.
- The script container can be in <head> or <body>.
- You have to define functions in <script> container
<script>
function PrintPage(){
window.print();
}
</script>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function PrintPage(){
window.print();
}
</script>
</head>
<body>
<h2>JavaScript - ES6</h2>
<button onclick="PrintPage()">Print</button>
<button onclick="PrintPage()">Print Page</button>
</body>
</html>
6
b) Compiled
If your JavaScript is used with HTML in browser then MIME type is defined as
"text/javascript" - Interpretted
"text/babel" - JavaScript is used with babel compiler
"text/module" - JavaScript module system
Syntax:
<script type="text/javascript"> </script>
<script type="text/babel"> </script>
You can turn on strict mode by using "use strict"; in your code snippet.
EX:
<script>
"use strict";
x = 10; // invalid - x is not defined // valid if strict off
document.write("x=" + x);
</script>
FAQ: How to target JavaScript for Legacy browsers? [Old Version Browsers]
Ans : Developer can target new JavaScript code to the legacy browser by enclosing the code in HTML
comments.
Syntax
<script type="text/javascirpt">
<!--
"use strict";
......
......
-->
</script>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
<!--
"use strict";
function PrintPage(){
window.print();
}
-->
</script>
</head>
<body>
<!--this is body section-->
<h2>JavaScript Embedded</h2>
<button onclick="PrintPage()">Print</button>
7
</body>
</html>
index.js
<!--
"use strict";
function PrintPage(){
window.print();
}
-->
- You can link the script file to any HTML page by using <script> element.
- Features
Clean spearation of code and design.
Hard to test if it is embedded , [easy]
Hard to extend if it is embedded , [easy]
- Issue
Using a external file for HTML page will increase the number of requests.
If number of requests are increased for page, then page load time will increase.
Ex: src/scripts
index.js
<!--
"use strict";
function PrintPage(){
window.print();
}
-->
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="src/scripts/index.js">
</script>
</head>
<body>
<!--this is body section-->
<h2>JavaScript External File</h2>
<button onclick="PrintPage()">Print</button>
8
</body>
</html>
Minification
- It is coding technique used by developers to reduce the size of file. [Compress]
- Minified files are used in Production
- Unminified files are use is Development
Ex:
1. Visit any minification site "https://www.toptal.com/developers/javascript-minifier"
3. Minify
index.min.js
Bundling
[WebPack, Parcel]
Ex:
index.js
function bodyload(){
window.document.images[0].src = "public/images/shoe.jpg";
window.document.images[0].width = 200;
window.document.forms[0].elements[0].value = "Register";
window.document.forms[1].elements[1].value = "Login";
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
9
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="src/scripts/index.js"></script>
</head>
<body onload="bodyload()">
<img width="100" height="100" border="1">
<div>
<form>
<h2>Reigster</h2>
Your Email <input type="button"> <input type="email">
</form>
</div>
<div>
<form>
<h2>Login</h2>
Your Mobile : <input type="text"> <input type="button">
</form>
</div>
</body>
</html>
Ex:
index.js
function bodyload(){
pic.src = "public/images/shoe.jpg";
pic.width = 200;
frmRegister.btnRegister.value = "Register";
frmLogin.btnLogin.value = "Login";
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="src/scripts/index.js"></script>
</head>
<body onload="bodyload()">
<img name="pic" width="100" height="100" border="1">
<div>
<form name="frmRegister">
<h2>Reigster</h2>
Your Email <input type="email"> <input type="button" name="btnRegister">
</form>
</div>
10
<div>
<form name="frmLogin">
<h2>Login</h2>
Your Mobile : <input type="text"> <input name="btnLogin" type="button">
</form>
</div>
</body>
</html>
Ex:
index.js
function bodyload(){
document.getElementById("pic").src = "public/images/shoe.jpg";
document.getElementById("btnRegister").value = "Register";
document.getElementById("btnLogin").value = "Login";
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="src/scripts/index.js"></script>
</head>
<body onload="bodyload()">
<img name="pic" id="pic" width="100" height="100" border="1">
<div>
<form name="frmRegister">
<h2>Reigster</h2>
Your Email <input type="email"> <input id="btnRegister" type="button" name="btnRegister">
</form>
</div>
<div>
<form name="frmLogin">
<h2>Login</h2>
Your Mobile : <input type="text"> <input id="btnLogin" name="btnLogin" type="button">
</form>
</div>
</body>
</html>
11
Dynamic Pseudo classes
Structural Pseudo classes
Element state pseudo classes
Validation state pseudo classes
Ex:
index.js
function bodyload(){
document.querySelector("img").src = "public/images/shoe.jpg";
document.querySelector("#btnRegister").value = "Register";
document.querySelector(".btn-login").value = "Login";
document.querySelector("nav div img").src = "public/images/shoe.jpg";
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="src/scripts/index.js"></script>
</head>
<body onload="bodyload()">
<img name="pic" id="pic" width="100" height="100" border="1">
<nav>
<div>
<img width="300" height="200">
</div>
</nav>
<div>
<form name="frmRegister">
<h2>Reigster</h2>
Your Email <input type="email"> <input id="btnRegister" type="button" name="btnRegister">
</form>
</div>
<div>
<form name="frmLogin">
<h2>Login</h2>
Your Mobile : <input type="text"> <input id="btnLogin" class="btn btn-login" name="btnLogin"
type="button">
</form>
</div>
</body>
</html>
document.getElementsByTagName()
document.getElementsByClassName()
document.getElementsByName()
12
Day 6 : JavaScript Output Methods – 06/03/23
Summary
- Introduction to JavaScript
- Integrating JavaScript into HTML page [Client Side]
a) Inline
b) Embedded
c) External Files
d) Minification
- Strict Mode
- Legacy Browsers
- MIME Type
- JavaScript HTML reference methods
a) DOM hierarchy
b) By using Name
c) By using ID
d) By query selector
alert()
confirm()
document.write()
console methods
innerHTML
outerHTML
innerText
alert()
- It is used to display output in a message box.
- Message box pops-up in browser window.
- It comprises of only "OK", you can't cancel.
- Using "esc" key you can cancel.
Syntax:
alert("message"); // single line
alert("message\n line2"); // multiple lines
Ex:
index.js
function DeleteClick()
{
alert("Delete\nRecord will be deleted");
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
13
<script type="text/javascript" src="src/scripts/index.js"></script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>
confirm()
- It is similar to alert but allows to cancel.
- It is boolean method that returns
true = OK
false = Cancel
Syntax:
confirm("Message\nLine2"); // true or false
Ex:
index.js
function DeleteClick()
{
flag = confirm("Delete\nRecord will be deleted");
if(flag==true){
alert("Record Deleted..");
} else {
alert("You canceled..");
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="src/scripts/index.js"></script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>
document.write()
- It is an output method, which can display output on a new screen.
[It is on same page but a new screen]
Syntax:
document.write("message"); \\ no "\n" for line break
document.write(<markup>); \\ <br>
Ex:
index.js
14
function DeleteClick()
{
flag = confirm("Delete\nRecord will be deleted");
if(flag==true){
document.write("<b><i><font color=red>Record Deleted..</font></b>");
} else {
alert("You canceled..");
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="src/scripts/index.js"></script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>
innerText
- It can display output in any container of HTML page, which can show text.
- It will not allow formats for text.
- It is only for plain text content.
- Markup not allowed for output.
Syntax:
document.querySelector("reference").innerText = "message";
Ex:
index.js
function DeleteClick()
{
flag = confirm("Delete\nRecord will be deleted");
if(flag==true){
document.querySelector("h2").innerText = "Delete Confirmed";
document.querySelector("p").innerText = "Record Deleted Successfully..";
} else {
alert("You canceled..");
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
15
<script type="text/javascript" src="src/scripts/index.js"></script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
<h2></h2>
<p></p>
</body>
</html>
innerHTML
- It is similar to innerText but allows formats with markup or functions.
Syntax:
document.querySelector("reference").innerHTML = "markup/message";
index.js
function DeleteClick()
{
flag = confirm("Delete\nRecord will be deleted");
if(flag==true){
document.querySelector("h2").innerHTML = "<font color=red>Delete Confirmed</font>";
document.querySelector("p").innerHTML = "<i><font color=red>Record Deleted
Successfully..</font></i>";
} else {
alert("You canceled..");
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="src/scripts/index.js"></script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
<h2></h2>
<p></p>
</body>
</html>
Ex:
index.js
function DeleteClick()
{
flag = confirm("Delete\nRecord will be deleted");
if(flag==true){
document.querySelector("input[type=text]").value = "Delete Confirmed";
} else {
alert("You canceled..");
}
}
16
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="src/scripts/index.js"></script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
<input type="text">
</body>
</html>
outerHTML
- It can replace the target markup with the specified.
Syntax:
document.querySelector("targetElement").outerHTML = "<newElement>";
Ex:
index.js
function DeleteClick()
{
flag = confirm("Delete\nRecord will be deleted");
if(flag==true){
document.querySelector("p").outerHTML = "<h2>Delete Confirmed</h2>";
} else {
alert("You canceled..");
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="src/scripts/index.js"></script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
<p></p>
</body>
</html>
console
- It is a developer tool.
- Developer can test all his logic in console.
17
- Developer can log information in console with various contextual messages
warning
success
error
debug
info
Syntax:
console.log(), debug(), info(), error(), warn() ...
Ex:
index.js
function DeleteClick()
{
console.log("Delete Button Clicked");
flag = confirm("Delete\nRecord will be deleted");
if(flag==true){
console.warn("OK Button Clicked - Record will delete");
document.querySelector("p").outerHTML = "<h2>Delete Confirmed</h2>";
} else {
alert("You canceled..");
console.error("Cancel Clicked");
}
}
18
Query String
page.html ? uname=john
page.html ? uname=john&age=23
- Querystring is accessed and used in page by using Browser Object [BOM] "location".
Ex:
index.js
function bodyload(){
string = location.search;
username = string.substring(string.indexOf("=")+1);
document.querySelector("span").innerHTML = username;
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="src/scripts/index.js"></script>
</head>
<body onload="bodyload()">
Your Name: <span></span>
</body>
</html>
prompt()
- It is an input box provided by browser to accept input from user.
Syntax :
prompt("Message", "default_value");
prompt("Message");
- Prompt returns
19
Ex:
index.js
function bodyload(){
username = prompt("Enter User Name");
age = prompt("Enter Age");
if(username=="") {
alert("Name can't be empty");
} else if(username==null) {
alert("You Canceled");
} else {
document.querySelector("span").innerHTML = username + "<br>" + "Your Age :" + age ;
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="src/scripts/index.js"></script>
</head>
<body onload="bodyload()">
Your Name: <span></span>
</body>
</html>
Ex:
index.js
function CreateClick(){
folderTextBox = document.getElementById("FolderName");
error = document.getElementById("Error");
if(folderTextBox.value=="") {
error.innerHTML = "Folder Name Required";
} else {
20
document.querySelector("p").innerHTML += folderTextBox.value + "<br>";
folderTextBox.value = "";
error.innerHTML = "";
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="src/scripts/index.js"></script>
</head>
<body>
<input type="text" id="FolderName" placeholder="Folder Name"> <button
onclick="CreateClick()">Create Folder</button>
<div id="Error" style="color:red"></div>
<p></p>
</body>
node_modules
bootstrap/dist/css/bootstrap.css
bootstrap-icons/font/bootstrap-icons.css
jquery/dist/jquery.js
bootstrap/dist/js/bootstrap-bundle.js
bootstrap/dist/js/popper.js
21
2. Link all bootstrap file to your HTML page
input-demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Input Demo</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-icons.css">
<script src="../src/scripts/input-demo.js"></script>
</head>
<body class="container-fluid">
<div id="RegisterContainer">
<h2>JavaScript Form Input</h2>
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#register">Register
Product</button>
</div>
22
<dd>
<input class="form-control" type="date" id="Manufactured">
</dd>
</dl>
</div>
<div class="modal-footer">
<button id="btnModelRegister" data-bs-dismiss="modal" onclick="RegisterClick()"
class="btn btn-success">Register</button>
<button class="btn btn-danger" data-bs-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="../node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
</body>
</html>
input-demo.js
function RegisterClick(){
document.getElementById("DetailsContainer").style.display = "block";
document.getElementById("RegisterContainer").style.display = "none";
document.getElementById("lblName").innerHTML = document.getElementById("Name").value ;
document.getElementById("lblPrice").innerHTML = document.getElementById("Price").value ;
23
document.getElementById("lblCity").innerHTML = document.getElementById("City").value ;
document.getElementById("lblMfd").innerHTML =
document.getElementById("Manufactured").value;
stockStatus = "";
stockCheckBox = document.getElementById("Stock");
if(stockCheckBox.checked) {
stockStatus = "Available";
} else {
stockStatus = "Out of Stock";
}
document.getElementById("lblStock").innerHTML = stockStatus;
function EditClick(){
document.getElementById("btnModelRegister").innerHTML = "Save";
document.getElementById("btnModelRegister").className = "btn btn-info";
}
Task:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inox Movies</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-icons.css">
</head>
<body class="container-fluid">
<h2>Inox Movies</h2>
<button class="btn btn-danger" data-bs-target="#movies" data-bs-toggle="modal">Book
Ticket</button>
<div class="modal" id="movies">
<div class="modal-dialog modal-fullscreen">
<div class="modal-content">
<div class="modal-header">
<h4>Book Ticket</h4>
<button class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="d-flex justify-content-around">
<div>
<select class="form-select">
<option>Select Movie</option>
<option>Top Gun - Maverick</option>
<option>Pathaan - Hindi</option>
</select>
24
</div>
<div>
<select class="form-select">
<option>Select Cinema</option>
<option>Inox GVK </option>
<option>Inox Ammerpet</option>
</select>
</div>
<div>
<select class="form-select">
<option>Select Date</option>
<option>Today 08-March </option>
<option>Tomorrow 09-March</option>
</select>
</div>
<div>
<select class="form-select">
<option>Select Time</option>
<option> 10:30 AM </option>
<option> 5:40 PM</option>
</select>
</div>
<div>
<select class="form-select">
<option>Select Seats</option>
<option>1</option>
<option>2</option>
</select>
</div>
<div>
<button class="btn btn-danger">Book</button>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="../node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
</body>
</html>
Variables
- Variables are storage locations in memory, where you can store a value and use it as a part of any
expression.
a) Declaration
b) Assignment
c) Initialization
var x; declaring
x = 10; assignment
<script>
x = 10; // valid
document.write("x=" + x);
</script>
<script>
"use strict";
x = 10; //invalid x is not defined
document.write("x=" + x);
</script>
a) var
b) let
c) const
Var
- It defines a function scope variable
- You can declare in any block of a function and access from any another block in the same
function.
- It allows declaring, initialization and assignment.
Ex:
26
<script>
"use strict";
function f1(){
var x; // declaring
x = 10; // assignment
if(x==10)
{
var y = 20; // initialization
}
document.write("x=" + x + "<br>" + "y=" + y);
}
f1();
</script>
- Var allows shadowing. It is the process of re-declaring or re-initializing same name identifier within
the function scope.
Syntax:
<script>
"use strict";
var x = 10;
var x = 20; // shadowing
document.write("x=" + x);
</script>
Ex:
<script>
"use strict";
function f1(){
var x; // declaring
x = 10; // assignment
if(x==10)
{
x = 30; // assigning
x = 40; // assigning
var x;
x = 15; // shadowing
var y = 20; // initialization
y = 50; // assigning
var y = 60; // shadowing
}
document.write("x=" + x + "<br>" + "y=" + y);
}
f1();
</script>
- Var allows hoisting. It is the process of declaring or initializing a variable after using .
Ex:
<script>
"use strict";
function f1(){
27
x = 10;
document.write("x=" + x);
var x; // hoisting
}
f1();
</script>
- Interpeter uses Lexical approach [bottom to top]
Let
- It is used to define a block scope variable.
- It is accessible within the specified block and its inner blocks.
{
block outer - a
{
block inner - a is accessible to inner
b - is not accessible to outer
}
}
const
- It is also block scope variable.
- It allows only initialization.
- It will not allow declaring and assigning.
- It will not allow shadowing and hoisting.
Syntax:
const x; // invalid
x = 10; // invalid
INOX – TASK :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inox Movies</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-icons.css">
</head>
<body class="container-fluid">
<h2>Inox Movies</h2>
<button class="btn btn-danger" data-bs-target="#movies" data-bs-toggle="modal">Book
Ticket</button>
28
<div class="modal" id="movies">
<div class="modal-dialog modal-fullscreen">
<div class="modal-content">
<div class="modal-header">
<h4>Book Ticket</h4>
<button class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="d-flex justify-content-around">
<div>
<select class="form-select">
<option>Select Movie</option>
<option>Top Gun - Maverick</option>
<option>Pathaan - Hindi</option>
</select>
</div>
<div>
<select class="form-select">
<option>Select Cinema</option>
<option>Inox GVK </option>
<option>Inox Ammerpet</option>
</select>
</div>
<div>
<select class="form-select">
<option>Select Date</option>
<option>Today 08-March </option>
<option>Tomorrow 09-March</option>
</select>
</div>
<div>
<select class="form-select">
<option>Select Time</option>
<option> 10:30 AM </option>
<option> 5:40 PM</option>
</select>
</div>
<div>
<select class="form-select">
<option>Select Seats</option>
<option>1</option>
<option>2</option>
</select>
</div>
<div>
<button class="btn btn-danger">Book</button>
</div>
</div>
</div>
</div>
</div>
29
</div>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="../node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
</body>
</html>
Ex:
<script>
"use strict";
var x = 10;
let y = 20;
const z = 30;
function f1()
{
document.write("function 1 <br> x=" + x + "<br>y=" + y + "<br>z=" + z + "<br>") ;
}
function f2()
{
document.write("function 2 <br> x=" + x + "<br>y=" + y + "<br>z=" + z + "<br>") ;
}
f1();
f2();
</script>
30
b) You can declare a global variable in side function using
"window" object.
Ex:
<script>
"use strict";
var x = 10;
let y = 20;
const z = 30;
function f1()
{
window.a = 100;
document.write("function 1 <br> x=" + x + "<br>y=" + y + "<br>z=" + z + "<br> a=" + a + "<br>") ;
}
function f2()
{
document.write("function 2 <br> x=" + x + "<br>y=" + y + "<br>z=" + z + "<br> a=" + a + "<br>") ;
}
f1();
f2();
</script>
var product2020;
var userPassword;
31
<script>
var x, y, z;
x = 10;
y = 20;
z = 30;
document.write("x=" + x +"<br>y=" + y + "<br>z=" + z);
</script>
<script>
var x, y=50, z;
x = 10;
z = 30;
document.write("x=" + x +"<br>y=" + y + "<br>z=" + z);
</script>
<script>
const x=10, y=50, z=30;
document.write("x=" + x +"<br>y=" + y + "<br>z=" + z);
</script>
<script>
const x=y=z=30;
document.write("x=" + x +"<br>y=" + y + "<br>z=" + z);
</script>
<script>
let y; // undefined
let x=y; // undefined
document.write("x=" + x + "<br>y=" + y);
</script>
- ES6 introduced de-structuring of variables, which allows to define multiple variables using "[ ]"
meta character.
- Variable allows object de-structuring, object comprises properties, values are stored under the
reference of a property.
32
var {property1, property2} = {property1:value, property2:value}
Ex:
<script>
const {rate, count} = {rate:4.3, count:2000};
document.write("Product Rating : " + rate + "<br> Count : " + count);
</script>
1. Primitive Types
2. Non-Primitive Types
Primitive Types
- They are Immutable types.
- Their structure can't be changed
- They have fixed range for values.
- They use a stack. [LIFO]
1. Number
2. String
3. Boolean
4. Null
5. Undefined
6. Symbol [ES6]
a) Number
b) String
c) Boolean
d) Null
e) Undefined
f) Symbol
g) Bigint
Number Type
- It represents a numeric value.
- A numeric value can be
Signed Integer -5
Unsigned Integer 5
Floating Point 34.30
Double 420.40
Decimal 4560.44 [29 places]
Exponent 2e3 [2 x 10(3) = 2000]
Hexa 0f0033 [0 to f]
Octa 0o748
Binary 0b1010
Bigint 2n [binary object] [bmp]
var x = 10;
var x = 2e3;
var x = 0o76;
var x = 0b1010;
- JavaScript is not strongly typed, so we have to explicitly verify the number type by using
"isNaN()".
Ex:
<script>
var age = prompt("Enter Age");
if(isNaN(age)){
document.write("Age must be number");
} else {
document.write("Your Age : " + age);
}
</script>
34
"10" can be converted
"10A" can be converted
"A10" invalid
"10A20" can be converted
- Parsing method
parseInt()
parseFloat()
<script>
var age = parseInt(prompt("Enter Age"));
document.write("Your Age : " + age + "<br>");
document.write("Next Your you will be : " + (age+1));
</script>
<script>
var rate = parseFloat(prompt("Interest Rate", "In %"));
var interest = rate / 12 / 100;
document.write("Interest = " + interest);
</script>
- JavaScript provides "Math" object to handle numeric expressions and mathematical operations .
- A developer can convert a mathematical or scientific equation into JavaScript expression by
using Math object
Math.PI
Math.sqrt
Math.min
Math.max
Math.avg
Math.cos
Math.sin
Math.pow etc..
- You can use "typeof" operator to check the data type of any reference value.
var x = 10;
document.write(typeof x);
Ex:
<script>
35
var age = parseInt(prompt("Enter Age"));
if((typeof age)=="number") {
document.write("You will be " + (parseInt(age)+1));
} else {
document.write("Please enter a number");
}
</script>
onload
onclick
Ex:
emi.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>EMI Calculator</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<style>
.box {
background-color: white;
box-shadow: 6px 6px 3px gray;
padding: 20px;
}
</style>
<script src="../src/scripts/emi.js" type="text/javascript"></script>
</head>
<body class="container-fluid">
<h1>Personal Loan EMI Calculator</h1>
<div class="box">
<div class="row">
<div class="col">
Amount you need ₹ <input type="text" onchange="AmountTextBoxChanged()"
id="txtAmount" size="10">
</div>
<div class="col">
for <input type="text" size="2" id="txtYears" onchange="YearTextBoxChanged()"> years
</div>
<div class="col">
interest rate <input type="text" id="txtRate" size="4" onchange="RateTextBoxChanged()"> %
</div>
</div>
<div class="row mt-4">
36
<div class="col">
<div class="d-flex">
<span>₹ 50,000 </span>
<input type="range" onchange="AmountChange()" id="rangeAmount" style="width:150px"
class="form-range" value="50000" min="50000" max="1000000">
<span>₹ 10,00,000</span>
</div>
</div>
<div class="col">
<div class="d-flex">
<span> 1 </span>
<input type="range" onchange="YearsChange()" id="rangeYears" style="width:150px"
class="form-range" value="1" min="1" max="5">
<span>5</span>
</div>
</div>
<div class="col">
<div class="d-flex">
<span> 10.25% </span>
<input type="range" id="rangeRate" onchange="RateChange()" style="width:150px"
class="form-range" value="10.25" step="0.01" min="10.25" max="18.45">
<span>18.45%</span>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col text-center">
<button onclick="CalculateClick()" class="btn btn-primary">Calculate</button>
</div>
</div>
</div>
<p style="font-size:30px" class="mt-3 text-center" id="result"></p>
</body>
</html>
emi.js
function AmountChange(){
document.getElementById("txtAmount").value = document.getElementById("rangeAmount").value;
}
function YearsChange(){
document.getElementById("txtYears").value = document.getElementById("rangeYears").value;
}
function RateChange(){
document.getElementById("txtRate").value = document.getElementById("rangeRate").value;
}
function CalculateClick(){
var p = parseInt(document.getElementById("txtAmount").value);
var n = parseInt(document.getElementById("txtYears").value) * 12;
var r = parseFloat(document.getElementById("txtRate").value)/12/100;
37
document.getElementById("rangeAmount").value = document.getElementById("txtAmount").value;
}
function YearTextBoxChanged(){
document.getElementById("rangeYears").value = document.getElementById("txtYears").value;
}
function RateTextBoxChanged(){
document.getElementById("rangeRate").value = document.getElementById("txtRate").value;
}
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BMI</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-icons.css">
<script>
function bodyload(){
var yourWeight = parseInt(prompt("Enter Weight"));
var yourStatus = document.getElementById("yourStatus");
if(yourWeight<53) {
yourStatus.style.marginLeft = "200px";
} else if(yourWeight>54 && yourWeight<70) {
yourStatus.style.marginLeft = "600px";
}
}
</script>
</head>
<body class="container-fluid" onload="bodyload()">
<h2>BMI Status</h2>
<div class="progress">
<div class="progress-bar bg-dark me-1" style="width:400px">
Underweight below 53 kg
</div>
<div class="progress-bar bg-success me-1" style="width:400px">
Normal Weight 54 to 70kg
</div>
<div class="progress-bar bg-warning me-1" style="width:400px">
Overweight 70 to 86 kg
</div>
<div class="progress-bar bg-danger" style="width:400px">
Obese above 86 kg
</div>
</div>
<div>
<div id="yourStatus">
<span class="bi bi-caret-down-fill"></span>
<div>You</div>
</div>
</div>
</body>
</html>
38
Day 13 : JavaScript String – 14/03/23
JavaScript String
- String is a literal with group of characters enclosed in
a) Double Quotes " "
b) Single Quotes ' '
c) Backticks ` `
- Double and Single quotes are used for inner and outer strings.
- String with single and double quote requires lot of contact technique with dynamic value.
[ string + dynamic + string ]
Syntax:
"string" + var + "string" + (expression) + "string";
Syntax:
`string ${var} string ${expression} string`
Ex:
<script>
var username = prompt("Enter Name");
var age = parseInt(prompt("Enter Age"));
var msg1 = "Hello !" + " " + username + " " + "you will be" + " " + (age+1) + " " + "next year.<br>" ;
var msg2 = `Hello ! ${username} you will be ${age+1} next year.<br>`;
var msg3 = 'Hello ! ${username} you will be ${age+1} next year.';
document.write(msg1);
document.write(msg2);
document.write(msg3);
</script>
Ex:
<script>
var title = prompt("Enter Title");
var loginName = prompt("Enter Login Name", "UserName, Email, Date");
var loginType = prompt("Enter Login Type", "Text|Email|Date");
var login = `
<form>
<h2>${title}</h2>
<dl>
<dt>${loginName}</dt>
<dd><input type=${loginType}></dd>
39
</dl>
<button>Login</button>
</form>
`;
document.write(login);
</script>
Note: Single and double quotes will not allow binding expressions.
Syntax:
var path = "D:\images\movie.jpg";
document.write(path);
D:imagesmovie.jpg
Syntax:
var path = "D:\\images\\movie.jpg";
D:\images\movie.jpg
40
- These string formatting functions must be used on "non-RC" type.
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String</title>
<script type="text/javascript">
function RegisterClick(){
var username = document.getElementById("UserName").value;
var userError = document.getElementById("UserError");
if(username=="")
{
userError.innerHTML = "User Name Required".fontcolor('red').fontsize(2).bold().italics() ;
} else {
document.write("Registered..");
}
}
function ChangeCase(){
var ifsc = document.getElementById("ifsc").value;
document.getElementById("ifsc").value = ifsc.toUpperCase();
}
</script>
</head>
<body>
<dl>
<dt>User Name</dt>
<dd><input type="text" id="UserName"></dd>
<dd id="UserError"></dd>
<dt>IFSC Code</dt>
<dd><input type="text" onkeyup="ChangeCase()" size="6" id="ifsc"></dd>
</dl>
<button onclick="RegisterClick()">Register</button>
</body>
</html>
string.style.attributeName = "value";
background-color backgroundColor
text-align textAlign
margin-left marginLeft
styles are not directly applied to string, they are defined to element
41
that handles string.
Ex:
if(username=="")
{
userError.innerHTML = "User Name Required";
userError.style.color = "red";
userError.style.fontWeight = "bold";
} else {
document.write("Registered..");
}
}
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String</title>
<style>
.error-style {
color:red;
font-weight: bold;
font-style: italic;
}
</style>
<script type="text/javascript">
function RegisterClick(){
var username = document.getElementById("UserName").value;
var userError = document.getElementById("UserError");
if(username=="")
{
userError.innerHTML = "User Name Required";
userError.className = "error-style";
} else {
document.write("Registered..");
}
}
function ChangeCase(){
var ifsc = document.getElementById("ifsc").value;
document.getElementById("ifsc").value = ifsc.toUpperCase();
}
</script>
42
</head>
<body>
<dl>
<dt>User Name</dt>
<dd><input type="text" id="UserName"></dd>
<dd id="UserError"></dd>
<dt>IFSC Code</dt>
<dd><input type="text" onkeyup="ChangeCase()" size="6" id="ifsc"></dd>
</dl>
<button onclick="RegisterClick()">Register</button>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String Format</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-icons.css">
<style>
.dark-theme {
padding: 10px;
background-color: black;
color:white;
}
</style>
<script>
function ThemeChange(){
var ThemeCheckbox = document.getElementById("ThemeCheckbox");
var frmLogin = document.getElementById("frmLogin");
var loginButton = document.querySelector("button");
if(ThemeCheckbox.checked) {
frmLogin.className = "dark-theme";
loginButton.className = "btn btn-light w-100";
} else {
frmLogin.className = "p-3";
loginButton.className = "btn btn-dark w-100";
}
}
</script>
</head>
<body class="container-fluid">
43
<div class="d-flex justify-content-center align-items-center" style="height:400px">
<form id="frmLogin">
<div class="form-switch">
<input type="checkbox" onchange="ThemeChange()" id="ThemeCheckbox" class="form-
check-input"> Dark Theme
</div>
<h2><span class="bi bi-personal-fill"></span> User Login</h2>
<dl>
<dt>User Name</dt>
<dd><input type="text" class="form-control"></dd>
<dt>Password</dt>
<dd><input type="password" class="form-control"></dd>
</dl>
<button class="btn btn-dark w-100">Login</button>
</form>
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String</title>
<script>
function SubmitClick(){
var UserName = document.getElementById("UserName").value;
var UserError = document.getElementById("UserError");
if(UserName==""){
UserError.innerHTML = "User Name Required".fontcolor('red');
} else {
document.write("Registered..");
}
}
function VerifyName(){
var UserName = document.getElementById("UserName").value;
var UserError = document.getElementById("UserError");
if(UserName.length<4) {
UserError.innerHTML = "Name too short min 4 chars".fontcolor('red');
} else {
UserError.innerHTML = "";
}
if(UserName.length>10) {
44
UserError.innerHTML = "Name too long max 10 chars".fontcolor('red');
}
if(UserName=="") {
UserError.innerHTML = "User Name Required".fontcolor('red');
}
}
</script>
</head>
<body>
<dl>
<dt>User Name</dt>
<dd><input type="text" onkeyup="VerifyName()" id="UserName"></dd>
<dd id="UserError"></dd>
</dl>
<button onclick="SubmitClick()">Submit</button>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function VerifyUser(){
var UserName = document.getElementById("UserName").value;
var UserError = document.getElementById("UserError");
if(UserName.charCodeAt(0)>=65 && UserName.charCodeAt(0)<=90) {
UserError.innerHTML = "";
} else {
UserError.innerHTML = "Name must start with uppercase letter".fontcolor('red') ;
}
}
</script>
</head>
45
<body>
User Name: <input type="text" onblur="VerifyUser()" id="UserName"> <span
id="UserError"></span>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function VerifyEmail(){
var Email = document.getElementById("Email").value;
var EmailError = document.getElementById("EmailError");
if(Email.indexOf("@")==-1) {
EmailError.innerHTML = "Invalid Email - Please include @ in Email".fontcolor('red');
} else {
EmailError.innerHTML = "";
}
}
</script>
</head>
<body>
Email : <input type="email" onblur="VerifyEmail()" id="Email"> <span id="EmailError"></span >
</body>
</html>
Syntax:
var str = "Welcome";
str.startsWith("w"); // false
str.startsWith("W"); // true
str.endsWith("e"); // true
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function VerifyEmail(){
var email = document.getElementById("Email").value;
var emailError = document.getElementById("EmailError");
if(email.endsWith("outlook.com")) {
emailError.innerHTML = "";
} else {
emailError.innerHTML = "Please provide a valid Skype Account".fontcolor('red');
}
}
function VerifyCard(){
var card = document.getElementById("Card").value;
var pic = document.getElementById("pic");
if(card.startsWith("44")){
pic.src="../public/images/visa.png";
} else if (card.startsWith("55")){
pic.src="../public/images/master.png";
} else {
pic.src = "";
pic.alt = "N/A";
}
}
</script>
</head>
<body>
<dl>
<dt>Your Skype Account</dt>
<dd><input type="email" onblur="VerifyEmail()" placeholder="@outlook" id="Email"></dd >
<dd id="EmailError"></dd>
47
<dt>Your Card Number</dt>
<dd><input type="text" onkeyup="VerifyCard()" id="Card"><img width="50" align="left"
height="20" id="pic"></dd>
</dl>
</body>
</html>
Syntax:
slice(startIndex, endIndex) => chars between specified index
slice(startIndex) => chars from start to end index
slice(7,4) => It can't read, end index must be
the index after start.
Syntax:
substr(startIndex, howMany)
substr(7, 4); => from 7 it reads 4 chars
substr(7,0); => will not read any chars
substr(7); => read upto end
Syntax:
substring(startIndex, endIndex) => end Index can be any direction
substring(7) => from 7 to end
substring(7,0) => from 7 to 0 [start]
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function GetDetails(){
var email = document.getElementById("Email").value;
var atPos = email.indexOf("@");
var id = email.substring(atPos,0);
var domain = email.substring(atPos + 1);
document.getElementById("Id").innerHTML = id;
document.getElementById("domain").innerHTML = domain;
}
</script>
</head>
<body>
Your Email : <input type="email" onblur="GetDetails()" id="Email">
48
<dl>
<dt>Your ID</dt>
<dd id="Id"></dd>
<dt>Domain</dt>
<dd id="domain"></dd>
</dl>
</body>
</html>
Syntax:
string.split(' char ');
Ex:
<script>
var products = "Samsung TV-46000.44, Nike Casuals-5000.44";
var [tv, shoe] = products.split(',');
var [name, price] = shoe.split('-');
document.write(`<h2>Shoe Details</h2>
Name : ${shoe.substring(shoe.indexOf("-"),0)} <br>
Price: ${shoe.substring(shoe.indexOf("-")+1)} <br>
<hr>
Shoe Name: ${name} <br>
Shoe Price: ${price}
`);
</script>
Ex:
<script>
var products = "Samsung TV-46000.44, Nike Casuals-5000.44";
var [tv, shoe] = products.split(',');
var details = shoe.split('-');
document.write(`<h2>Shoe Details</h2>
Name : ${shoe.substring(shoe.indexOf("-"),0)} <br>
Price: ${shoe.substring(shoe.indexOf("-")+1)} <br>
<hr>
Shoe Name: ${details[0]} <br>
Shoe Price: ${details[1]}
`);
</script>
Syntax:
string.trim()
Ex:
<!DOCTYPE html>
<html lang="en">
49
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function SubmitClick(){
var UserId = document.getElementById("UserId").value;
if(UserId.trim()=="john_nit") {
document.write("Success..");
} else {
alert("Invalid UserId");
}
}
</script>
</head>
<body>
Your UserId:
<input type="text" id="UserId">
<button onclick="SubmitClick()">Submit</button>
</body>
</html>
Syntax:
string.match(/regularExpression/);
Meta Characters
-----------------------
? zero or one occurance of a character.
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function SubmitClick(){
var test = document.getElementById("test").value;
if(test.match(/colou?r/)) {
document.write(`Your entered : ${test}`);
} else {
alert("Only Color | Colour Allowed");
}
50
}
</script>
</head>
<body>
Your string : <input type="text" id="test"> <button onclick="SubmitClick()">Submit</button >
</body>
</html>
Text Attributes
- name
- id
- class
- value
- size
- placeholder
- autofocus
- minlength
- maxlength
- required
- list
- pattern : It uses a regular expression to verify the format of input.
- disabled
- readonly
Ex: gmail\.com
51
| It is used as OR, allows multiple choices
Ex: red|green|blue
Ex: \^........$
Ex: \d => 1, 4, 6, 2, 3
\d\d => 22, 11, 24, 13
\d?\d => 1, 33, 35
Ex: colour\i
() Union of chars
52
[a-mA-M0-4] Only specified range of chars allowed
Quantifiers
Ex: \d{4,7}
pattern="\+91\d{10}" | \+91[0-9]{10}
+(1)(425) 555-0100 - US
+(44)(20) 1234 5678 - UK
pattern="\+\(1\)\(\d{3}\)\s\d{3}-\d{4}"
"\+\(\d{2}\)\(\d{2}\)\s\d{4}\s\d{4}"
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
53
function SubmitClick(){
var test = document.getElementById("test").value;
if(test.match(/\+\(1\)\(\d{3}\)\s\d{3}-\d{4}/)) {
document.write(`Your entered : ${test}`);
} else {
alert("Invalid - +(1)(425) 555-0100");
}
}
</script>
</head>
<body>
Your string : <input type="text" id="test"> <button onclick="SubmitClick()">Submit</button >
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function SubmitClick(){
var test = document.getElementById("test").value;
if(test.match(/(?=.*[A-Z])\w{4,10}/)) {
document.write(`Your entered : ${test}`);
} else {
alert("Invalid - Name 4 to 10 chars with atleast one uppercase letter");
}
}
</script>
</head>
<body>
Your string : <input type="text" id="test"> <button onclick="SubmitClick()">Submit</button >
</body>
</html>
Task:
1. Write expression for validating email address
2. Write expression for validating date format mm-dd-yyyy
3. Write expression for validating name 4 to 15 chars with at least one uppercase, number and
special char.
if(countryName=="India") {
flag.src = "images/india.png";
txtMobile.placeholder = "+91 and 10 digits";
regExp = /\+91\d{10}/;
} else if (countryName=="US") {
flag.src = "images/us.png";
txtMobile.placeholder = "+(1)(425) 555-0100";
regExp = /\+\(1\)\(\d{3}\)\s\d{3}-\d{4}/;
} else if (countryName=="UK") {
flag.src = "images/uk.png";
txtMobile.placeholder = "+(44)(20) 1234 5678";
regExp = /\+\(44\)\(\d{2}\)\s\d{4}\s\d{4}/;
}
}
function RegisterClick(){
var mobile = document.getElementById("txtMobile").value;
var mobileError = document.getElementById("mobileError");
if(mobile.match(regExp)){
document.write("Registered...");
} else {
mobileError.innerHTML = `Invalid Mobile -
${document.getElementById("txtMobile").placeholder}`;
}
}
</script>
</head>
<body class="container-fluid">
<h2>Verify Mobile</h2>
<dl class="w-50">
<dt>Your Country</dt>
<dd class="input-group">
<select id="lstCountries" class="form-select" onchange="CountryChanged()">
<option>Select Country</option>
<option>India</option>
<option>US</option>
55
<option>UK</option>
</select>
<img width="80" height="40" id="flag" border="1" class="input-group-text">
</dd>
<dt>Your Mobile</dt>
<dd>
<input type="text" class="form-control" id="txtMobile">
</dd>
<dd class="text-danger" id="mobileError"></dd>
</dl>
<button onclick="RegisterClick()" class="btn btn-primary">Register</button>
</body>
</html>
Boolean Types
true = 1
false = 0
var x = true;
var y = false;
if(x==1) // OK x == true
{
}
true + true = ? 2
true + "A" = ? trueA
true + 10 = ? 11
Ex:
<script>
var x = true;
if(x==1) { x==true Good
document.write("X is true");
} else {
document.write("x is false");
}
</script>
56
- selected
- required
- readonly
- disabled
- border [0, 1]
e1 e2
e1+e2
e1~e2
div~p
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function StockChanged(){
var stockCheckBox = document.getElementById("Stock");
var lblStock = document.getElementById("lblStock");
lblStock.innerHTML = (stockCheckBox.checked)?"Available":"Out of Stock";
}
</script>
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-icons.css">
<script>
function SortClick(){
var span = document.querySelector("button span");
span.className = (span.className=="bi bi-sort-alpha-down")? "bi bi-sort-alpha-up" : "bi bi-
sort-alpha-down";
}
</script>
</head>
<body>
<h2>Check Box Toggle</h2>
<input type="checkbox" onchange="StockChanged()" id="Stock"> <span id="lblStock">Out of
Stock</span>
<h2>Button Toggle</h2>
<button id="sort" onclick="SortClick()">
<span class="bi bi-sort-alpha-down"></span>
</button>
</body>
</html>
57
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function StockChanged(){
var stockCheckBox = document.getElementById("Stock");
var lblStock = document.getElementById("lblStock");
lblStock.innerHTML = (stockCheckBox.checked)?"Available":"Out of Stock";
}
</script>
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-icons.css">
<script>
function SortClick(){
var span = document.querySelector("button span");
span.className = (span.className=="bi bi-sort-alpha-down")? "bi bi-sort-alpha-up" : "bi bi-
sort-alpha-down";
}
function VerifyName(){
var txtName = document.getElementById("txtName");
var btnRegister = document.getElementById("btnRegister");
if(txtName.value=="") {
btnRegister.disabled = true;
} else {
btnRegister.disabled = false;
}
}
</script>
</head>
<body>
<h2>Your Name</h2>
<input type="text" onblur="VerifyName()" id="txtName"> <button disabled
id="btnRegister">Register</button>
<h2>Check Box Toggle</h2>
<input type="checkbox" onchange="StockChanged()" id="Stock"> <span id="lblStock">Out of
Stock</span>
<h2>Button Toggle</h2>
<button id="sort" onclick="SortClick()">
<span class="bi bi-sort-alpha-down"></span>
</button>
</body>
</html>
58
Day 18 : Undefined Null and Symbol Type – 23/03/23
JavaScript Data Types
- Number
- String
- Boolean
var x = 10;
x.toString()
Ex:
<script>
var x = "true";
var y = (x=="true")?true:false;
document.write(`
X is ${typeof x} <br>
Y is ${typeof y}
`);
</script>
undefined type
--------------------
- It specifies that there is no value defined in a reference.
var x;
document.write("x=" + x); x = undefined
- Undefined is a marker, that marks the variable to specifiy that there is no value defined .
- You can use "undefined" keyword to verify the value in any reference.
Ex:
<script>
var name = "Samsung TV";
var price = 10300.33;
59
if(price==undefined) { => not good
document.write("Name = " + name);
} else {
document.write(`Name=${name}<br>Price=${price}`);
}
</script>
<script>
var name = "Samsung TV";
var price;
if(price){
document.write(`Name=${name}<br>Price=${price}`);
} else {
document.write(`Name=${name}`);
}
</script>
null type
------------
- Undefined is configured by javascript for any reference if value is not found during compile time .
- Null is configured by javascript for any reference if value is not found during run time .
- Null is related to exception.
Ex:
<script>
var price = prompt("Enter Price");
if(price==null) {
document.write(`You canceled - Please provide Price`);
}
else if(price=="") {
document.write(`Price can't be empty`);
}
else {
document.write(`Price=${price}`);
60
}
</script>
symbol type
- JavaScript introduced symbol type from ES6.
- Earlier JS uses symbol type implicitly.
- It is used to configure a unique identification key for objects.
{
UserName: "John",
Age : 22
}
- Symbol configures a hidden field in object, which is present in object but not used by iterators .
- Iterator is used to access all properties of object.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form>
<h2>Edit User Details</h2>
<dl>
<input type="hidden" name="UserId" value="john_nit">
<dt>User Name</dt>
<dd><input type="text" name="UserName"></dd>
<dt>Age</dt>
<dd><input type="number" name="Age"></dd>
</dl>
<button>Submit</button>
</form>
</body>
</html>
Ex:
<script>
var UserId = Symbol();
var userDetails = {
[UserId] : "john_nit",
UserName : "John",
Age: 22
}
for(var property in userDetails){
61
document.write(`${property} : ${userDetails[property]} <br>`);
}
document.write("User Id : " + userDetails[UserId] + "<br>");
</script>
FAQ: How to configure a field which can display value on screen but will not submit ?
Ans :
- If name is not defined for any field in a form then it can't submit.
- If field is not in form then it can't submit
- If field is disabled then it can't submit.
Array
- Arrays are used in computer programming to reduce overhead and complexity .
- Array reduces overhead by storing values in sequential order.
- Array can reduce complexity by storing multiple values under one name.
- JavaScript array can store any type of value, which is not possible for several programming
languages.
- Array can change its size dynamically in JavaScript.
- Array refers to a formation where items are in order but can be accessed random.
Configuring Array
------------------------
Array configuration comprises of 2 phases
1. Declaring Array
2. Initializing memory or assigning memory for array
Syntax: Declaring
var products;
let products;
const products; // it requires initializaiton
62
var products = [ ];
var products = new Array();
(or)
var products;
products = [ ];
products = new Array();
Syntax: Initialization
var values = [ ];
values[1] = 10; [1] - string
values["2"] = 20; [2] - string
Ex:
<script>
var values = [10, "john", true];
values["3"] = "david";
for(var property in values)
{
document.write(`[${property}]-${typeof property} : ${values[property]}-${typeof
values[property]}<br>`);
}
document.write(values[2]);
</script>
Ex:
<script>
var values = [10, "TV", true, ["Delhi", "Hyd"], function(){document.write("Hello !")}];
63
document.write(values[3][1] + "<br>");
values[4]();
</script>
<script>
var values = [10, "TV", true, ["Delhi", "Hyd"], function(){document.write("Hello !")}];
var [id, name, stock, cities, hello] = values;
document.write(cities[1] + "<br>");
hello();
</script>
Array Manipulations
- JavaScript array object provides a set of properites and methods to control array .
Ex:
<script>
var categories = ["Electronics", "Footwear", "Fashion"];
document.write(categories.toString() + "<br>");
document.write(categories.join("==>") + "<br>");
document.write(categories.slice(1,2) + "<br>");
categories.map(function(category){
document.write(`<button>${category}</button><br>`);
})
</script>
Ex:
<script>
var sales = [35000, 57000, 24400, 67000, 21000];
var result = sales.find(function(value){
return value>50000;
})
document.write(result);
</script>
Ex:
<script>
var sales = [35000, 57000, 24400, 67000, 21000];
var result = sales.filter(function(value){
64
return value>50000;
})
document.write(result);
</script>
toString()
join()
map()
find()
filter()
slice()
for..in
for..of
for..in
- It is an iterator used to read all properties from array.
Syntax:
for(var property in collection)
{
}
for..of
- It is an iterator used to read all elements [values] from array.
Syntax:
for(var item of collection)
{
}
<script>
var sales = [35000, 57000, 24400, 67000, 21000];
for(var property in sales){
document.write(`[${property}]-${sales[property]}<br>`);
}
</script>
Syntax:
collection.push("item1", "item2", ...);
collection.unshift("item1", "item2",..);
collection.splice(indexNumber, deleteCount, "item1", "item2"..);
Ex:
<script>
var categories = ["Electronics", "Footwear", "Fashion"];
categories.unshift("All");
categories.splice(2,0,"Kids", "Men's Clothing");
for(var property in categories)
{
document.write(`[${property}] ${categories[property]}<br>`);
}
</script>
Ex:
<script>
var categories = ["Electronics", "Footwear", "Fashion"];
document.write(`${categories.splice(1,2)} removed.<br>`);
for(var property in categories)
{
66
document.write(`[${property}] ${categories[property]}<br>`);
}
</script>
Ex:
<script>
var categories = ["Electronics", "Footwear", "Fashion"];
categories.length = 0;
document.write(categories);
</script>
Ex:
<script>
var categories = ["Electronics", "Footwear", "Fashion"];
categories = [];
document.write(categories);
</script>
Ex:
<script>
var categories = ["Electronics", "Footwear", "Fashion"];
var menu = categories;
document.write(`
Categories : ${categories} <br>
Menu : ${menu}
`);
</script>
<script>
var categories = ["Electronics", "Footwear", "Fashion", "Kids", "Men"];
var menu = JSON.parse(JSON.stringify(categories));
document.write(`
Categories : ${categories} <br>
67
Menu : ${menu}
`);
</script>
Ex:
<script>
var cities = ["Delhi","Hyd","Mumbai", "Chennai", "Bangalore"];
cities.sort();
cities.reverse();
for(var item of cities) {
document.write(item + "<br>");
}
</script>
ref.id
ref.name
ref.className
ref.width
ref.height
ref.src
appendChild(newElement);
document.querySelector("body").appendChild(ref);
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
68
<script>
function AddClick(){
var pic = document.createElement("img");
pic.width = "200";
pic.height = "200";
pic.border = "2";
pic.src = "../public/images/shoe.jpg";
document.getElementById("container").appendChild(pic);
}
</script>
</head>
<body>
<button onclick="AddClick()">Add Image</button>
<div id="container">
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function AddClick(){
var pic = document.createElement("img");
pic.width = "200";
pic.height = "200";
pic.border = "2";
pic.src = "../public/images/shoe.jpg";
document.getElementById("container").appendChild(pic);
}
function AddOption(){
var option = document.createElement("option");
option.text = "Delhi";
option.value = "Delhi";
document.querySelector("select").appendChild(option);
}
</script>
</head>
<body>
<button onclick="AddClick()">Add Image</button>
<button onclick="AddOption()">Add Option</button>
<div id="container">
</div>
<select>
69
</select>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var categories = ["All", "Electronics", "Footwear", "Fashion"];
function AddOption(){
document.querySelector("select").innerHTML = "";
for(var item of categories){
var option = document.createElement("option");
option.text = item;
option.value = item;
document.querySelector("select").appendChild(option);
}
}
</script>
</head>
<body>
<button onclick="AddOption()">Add Option</button>
<select>
</select>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var categories = ["All", "Electronics", "Footwear", "Fashion"];
function AddOption(){
document.querySelector("select").innerHTML = "";
for(var item of categories){
70
var option = document.createElement("option");
option.text = item;
option.value = item;
document.querySelector("select").appendChild(option);
var li = document.createElement("li");
li.innerHTML = item;
document.querySelector("ol").appendChild(li);
var tr = document.createElement("tr");
var td = document.createElement("td");
td.innerHTML = item;
tr.appendChild(td);
document.querySelector("tbody").appendChild(tr);
}
}
</script>
</head>
<body>
<button onclick="AddOption()">Add Option</button>
<select>
</select>
<h2>Categories</h2>
<ol>
</ol>
<h2>Table</h2>
<table border="1" width="400">
<thead>
<tr>
<th>Categories</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
72
}
function SortAsc(){
cities.sort();
LoadCities();
}
function SortDsc(){
cities.sort();
cities.reverse();
LoadCities();
}
</script>
</head>
<body class="container-fluid" onload="bodyload()">
<h2>Array Manipulations</h2>
<div class="mt-3 mb-3 w-25">
<div class="input-group">
<span class="input-group-text">New City : </span>
<input type="text" id="txtCity" class="form-control">
<button onclick="AddClick()" class="btn btn-primary">Add</button>
</div>
</div>
<div class="w-25">
<label class="form-label">Your Cities</label>
<div>
<div class="mt-2 mb-2">
<button class="btn btn-primary" onclick="SortAsc()">
<span class="bi bi-sort-alpha-down"></span>
</button>
<button class="btn btn-primary" onclick="SortDsc()">
<span class="bi bi-sort-alpha-up"></span>
</button>
</div>
<select class="form-select" size="3" id="lstCities">
</select>
<label class="form-label" id="lblCount"></label>
</div>
<div class="mt-3">
<button class="btn btn-danger" onclick="RemoveClick()"> <span class="bi bi-trash-
fill"></span>Remove City</button>
<button class="btn btn-danger" onclick="ClearClick()">Clear All</button>
</div>
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
73
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var photos = ["images/m1.jpg", "images/m2.jpg", "images/m3.jpg", "images/m4.jpg",
"images/m5.jpg"];
function bodyload(){
for(var path of photos) {
var img = document.createElement("img");
img.src = path;
img.width = "200";
img.height = "200";
document.getElementById("gallery").appendChild(img);
}
}
</script>
<style>
body {
height: 500px;
display: flex;
justify-content: center;
align-items: center;
}
img:hover {
transform: scale(1.5);
transition: 2s;
box-shadow: 10px 10px 3px gray;
}
img {
transition: 2s;
}
marquee {
padding: 100px;
}
</style>
</head>
<body onload="bodyload()">
<div>
<marquee scrollamount="10" id="gallery" onmouseover="this.stop()"
onmouseout="this.start()">
</marquee>
</div>
</body>
</html>
Object Type
- Object is set of properties and functions.
- Object is to store all related data and logic together.
74
- "Alan Kay" introduced the concept of Object into computer programming in early 1960's .
- Joahn Olay and Nygaard developer object oriented programming in early 1967.
- It was formulated with a language "SIMULA".
Syntax:
let tv = { }
- Data and logic is stored in object in the form of "Key - Value" collection.
Syntax:
let tv = {
Key : value,
Key : value
}
JSON
{
"Name": "Samsung TV",
"Price" : 30000.44,
"Stock" : true
}
XML
<Product>
<Name> Samsung TV </Name>
<Price> 30000.44 </Price>
<Stock> true </Stock>
</Product>
Ex:
<script>
var tv = {
"Name": "Samsung TV",
"Price": 50000.33,
"Stock": true,
"Cities": ["Delhi", "Hyd"],
"Rating": {"Rate":4.3, "Count": 3500}
}
document.write(`
Name : ${tv.Name} <br>
Price : ${tv.Price} <br>
Stock : ${tv.Stock} <br>
Cities: ${tv.Cities.toString()} <br>
75
Rating : ${tv.Rating.Rate} [${tv.Rating.Count}]
`);
</script>
Syntax:
var product = {
"Name": "TV",
"Price": 45000.44,
"Qty": 3,
"Total": function() {
},
"Print": function() {
}
}
- You can access the properties and functions with in object by using "this" keyword .
"Total": function() {
return this.Qty * this.Price;
}
- You can access the properties and functions outside object by using object reference .
product.Qty
product.Total()
product.Print()
Array of Objects
- To access data from JSON file or API URL browser needs "XMLHttpRequest" object.
- JavaScript provides a promise called "fetch()" which uses XMLHttpRequest.
- Promise is a function that returns accurate status of any task performed.
Promise Fullfilled
Promise Rejected
Promise Failed
Syntax:
fetch("url | path")
77
.then(function(){
on success
})
.catch(function(){
on failure
})
.finally(function(){
always..
})
Ex:
1. add a new folder into project
"data"
"flipkart.json"
{
"title": "vivo T1 44W (Midnight Galaxy, 128 GB) (4 GB RAM)",
"price": 14499,
"actualPrice":17999,
"offers": [
"Bank Offer10% off on Bank of Baroda Credit Card EMI Transactions, up to ₹1,000 on orders of
₹5,000 and aboveT&C",
"Bank Offer10% off on IDFC FIRST Bank Credit Card EMI Transactions, up to ₹1,000 on orders
of ₹5,000 and aboveT&C",
"Bank Offer10% off on IndusInd Bank Credit Card EMI Transactions, up to ₹1,000 on orders of
₹7,500 and aboveT&C",
"Buy this Product and Get Extra ₹500 Off on Bikes & ScootersT&C"
],
"rating": {"rate":4.5, "ratings":96490, "reviews": 5600},
"photo": "../public/images/m1.jpg"
}
flipkart.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flipkart</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-icons.css">
<script>
function bodyload(){
78
fetch("../data/flipkart.json")
.then(function(response){
return response.json();
})
.then(function(product){
document.getElementById("productImage").src= product.photo;
document.getElementById("productTitle").innerHTML = product.title;
document.getElementById("productRating").innerHTML = product.rating.rate;
document.getElementById("productReviews").innerHTML = `${product.rating.ratings}
Ratings & ${product.rating.reviews} Reviews`.fontcolor('gray').bold();
document.getElementById("productPrice").innerHTML = `₹ ${product.price} <font
size='5' color='gray'><strike> ₹ ${product.actualPrice}</strike></font>`;
for(var offer of product.offers){
var li = document.createElement("li");
li.innerHTML = `<span class="bi bi-tag-fill text-success"></span> ${offer}`;
li.className = "mb-2 mt-2";
document.querySelector("ul").appendChild(li);
}
})
}
</script>
</head>
<body class="container-fluid" onload="bodyload()">
<section class="row mt-4">
<div class="col-3">
<img width="300" height="400" id="productImage">
</div>
<div class="col-9">
<h3 id="productTitle"></h3>
<div class="d-flex">
<div class="bg-success text-white p-1 rounded" style="width:60px">
<span id="productRating"></span> <span class="bi bi-star-fill"></span>
</div>
<div class="ms-3">
<span id="productReviews"></span>
</div>
</div>
<div class="mt-4">
<h1 id="productPrice"></h1>
</div>
<div>
<h3>Offers</h3>
<ul>
</ul>
</div>
</div>
</section>
</body>
</html>
79
Day 23 : Fakestore and NASA API – 31/03/23
Nasa API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script>
function bodyload(){
fetch("https://api.nasa.gov/mars-
photos/api/v1/rovers/curiosity/photos?sol=1000&api_key=6ffzhNjjV1XA2HkP9u2ghEmZVMK8Rb
2M2ZG4n6Fl")
.then(function(res){
return res.json();
})
.then(function(marsObject){
console.log(marsObject);
for(var item of marsObject.photos)
{
var div = document.createElement("div");
div.className = "card p-2 m-2";
div.style.width = "200px";
div.innerHTML = `
<img src=${item.img_src} height="150" class="card-img-top">
<div class="card-header">
<h2>${item.id}</h2>
</div>
<div class="card-body">
<dl>
<dt>Camera</dt>
<dd>${item.camera.full_name}</dd>
<dt>Rover</dt>
<dd>${item.rover.name}</dd>
</dl>
</div>
`;
document.querySelector("main").appendChild(div);
}
})
}
</script>
</head>
<body class="container-fluid" onload="bodyload()">
<h2>Mars Rover Photos</h2>
<main class="d-flex flex-wrap">
80
</main>
</body>
</html>
Ex:
products.json
[
{
"Name": "Samsung TV",
"Price": 45000.44,
"Rating": {"Rate":4.3, "Count":5000}
},
{
"Name": "Nike Casuals",
"Price": 5700.33,
"Rating": {"Rate":3.6, "Count":3200}
},
{
"Name": "Watch",
"Price": 3500.33,
"Rating":{"Rate":4.2, "Count":5000}
}
]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function bodyload(){
fetch("../data/products.json")
.then(function(response){
return response.json();
})
.then(function(products){
for(var product of products){
var tr = document.createElement("tr");
var tdName = document.createElement("td");
var tdPrice = document.createElement("td");
var tdRating = document.createElement("td");
tdName.innerHTML = product.Name;
tdPrice.innerHTML = product.Price;
tdRating.innerHTML = `${product.Rating.Rate} [${product.Rating.Count}]`;
81
tr.appendChild(tdName);
tr.appendChild(tdPrice);
tr.appendChild(tdRating);
document.querySelector("tbody").appendChild(tr);
}
})
}
</script>
</head>
<body onload="bodyload()">
<table border="1" width="400">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Rating</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
Fakestore API
GET Requests
http://fakestoreapi.com
/products [ { }, { } ] 20
/products/1 { } specific product by id
/products/categories [""] list of all categories
/products/category/jewelery [{},{}] specific category products
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shopper|Online Shopping</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-icons.css">
<script type="text/javascript">
82
function LoadCategories(){
fetch("http://fakestoreapi.com/products/categories")
.then(function(response){
return response.json();
})
.then(function(categories){
categories.unshift("all");
for(var category of categories){
var option = document.createElement("option");
option.text = category.toUpperCase();
option.value = category;
document.getElementById("lstCategories").appendChild(option);
}
})
}
function LoadProducts(url){
document.querySelector("main").innerHTML="";
fetch(url)
.then(function(response){
return response.json();
})
.then(function(products){
for(var product of products){
var card = document.createElement("div");
card.className = "card p-2 m-2";
card.style.width = "200px";
card.innerHTML = `
<img src=${product.image} class="card-img-top" height="100">
<div class="card-header overflow-auto" style="height:80px">
<p>${product.title}</p>
</div>
<div class="card-body">
<dl>
<dt>Price</dt>
<dd>${product.price}</dd>
<dt>Rating</dt>
<dd>
<span class="bi bi-star-fill text-success"> </span>
${product.rating.rate} [${product.rating.count}]
</dd>
</dl>
</div>
<div class="card-footer">
<button onclick="AddToCartClick(${product.id})" class="btn btn-danger w-100">
<span class="bi bi-cart4"></span> Add to Cart
</button>
</div>
`;
document.querySelector("main").appendChild(card);
}
})
83
}
function bodyload(){
LoadCategories();
LoadProducts("http://fakestoreapi.com/products");
GetCartCount();
}
function CategoryChanged(){
var categoryName = document.getElementById("lstCategories").value;
if(categoryName=="all"){
LoadProducts("http://fakestoreapi.com/products");
} else {
LoadProducts(`http://fakestoreapi.com/products/category/${categoryName}`);
}
}
function NavClick(categoryName){
document.getElementById("lstCategories").value = categoryName;
if(categoryName=="all"){
LoadProducts("http://fakestoreapi.com/products");
} else {
LoadProducts(`http://fakestoreapi.com/products/category/${categoryName}`);
}
}
var cartItems = [];
function GetCartCount(){
document.getElementById("cartCount").innerHTML = cartItems.length;
}
function AddToCartClick(id) {
fetch(`http://fakestoreapi.com/products/${id}`)
.then(function(response){
return response.json();
})
.then(function(product){
alert(`${product.title}\nAdded to Cart`);
cartItems.push(product);
GetCartCount();
})
}
function LoadCartItems(){
document.querySelector("tbody").innerHTML= "";
for(var item of cartItems){
var tr = document.createElement("tr");
var tdTitle = document.createElement("td");
var tdImage = document.createElement("td");
var tdPrice = document.createElement("td");
var tdAction = document.createElement("td");
tdTitle.innerHTML = item.title;
tdImage.innerHTML = `<img src=${item.image} width="50" height="50">`;
tdPrice.innerHTML = item.price;
tdAction.innerHTML = `
<button class="bi bi-trash-fill btn btn-danger"></button>
84
`;
tr.appendChild(tdTitle);
tr.appendChild(tdImage);
tr.appendChild(tdPrice);
tr.appendChild(tdAction);
document.querySelector("tbody").appendChild(tr);
}
}
</script>
<style>
a{
color:white;
text-decoration: none;
}
a:hover {
color:yellow;
}
</style>
</head>
<body class="container-fluid" onload="bodyload()">
<header class="d-flex justify-content-between p-2 bg-dark text-white mt-2">
<div>
<span style="font-size:25px; font-weight:bold">Shopper.</span>
</div>
<div style="font-size: 20px;">
<span class="me-3"><a href="javascript:NavClick('all')">Home</a></span>
<span class="me-3"><a href="javascript:NavClick('electronics')">Electronics</a></span>
<span class="me-3"><a href="javascript:NavClick('jewelery')">Jewelery</a></span>
<span class="me-3"><a href="javascript:NavClick('men\'s clothing')">Men's
Fashion</a></span>
<span class="me-3"><a href="javascript:NavClick('women\'s clothing')">Women's
Fashion</a></span>
</div>
<div>
<span class="bi bi-search me-3"></span>
<span class="bi bi-person me-3"></span>
<span class="bi bi-heart me-3"></span>
<button onclick="LoadCartItems()" data-bs-target="#cart" data-bs-toggle="modal"
class="btn text-white position-relative">
<span class="bi bi-cart"></span>
<span id="cartCount" class="badge bg-danger position-absolute rounded rounded-
circle"></span>
</button>
<div class="modal fade" id="cart">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="text-primary">Your Cart Summary</h4>
<button class="btn-close" data-bs-dismiss="modal"></button>
85
</div>
<div class="modal-body">
<table class="table table-hover">
<thead>
<tr>
<th>Title</th>
<th>Preview</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</header>
<section class="mt-3 row">
<nav class="col-2">
<div>
<label class="form-label fw-bold">Select Category</label>
<div>
<select onchange="CategoryChanged()" class="form-select" id="lstCategories">
</select>
</div>
</div>
</nav>
<main class="col-10 d-flex flex-wrap overflow-auto" style="height:500px">
</main>
</section>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="../node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
</body>
</html>
function bodyload(){
for(var item of data) {
var li = document.createElement("li");
li.innerHTML = item.Category;
</ol>
<select>
</select>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
87
<title>Document</title>
<script>
var data = [
{Category:"Electronics", Products:["Televisions","Mobiles"]},
{Category:"Footwear", Products:["Casuals", "Boots"]}
];
function bodyload(){
for(var item of data) {
var details = document.createElement("details");
var summary = document.createElement("summary");
summary.innerHTML = item.Category;
details.appendChild(summary);
for(var product of item.Products){
var div = document.createElement("div");
div.innerHTML = product;
div.style.marginBottom = "20px";
div.style.marginLeft = "30px";
details.appendChild(div);
}
document.getElementById("menu").appendChild(details);
}
}
</script>
</head>
<body onload="bodyload()">
<div id="menu">
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var data = [
{Topic: "JavaScript", Description: "JavaScript is a language."},
{Topic: "HTML", Description: "It is a markup language."}
]
function bodyload(){
for(var item of data){
var dt = document.createElement("dt");
var dd = document.createElement("dd");
dt.innerHTML = item.Topic;
dd.innerHTML = item.Description;
88
document.querySelector("dl").appendChild(dt);
document.querySelector("dl").appendChild(dd);
}
}
</script>
</head>
<body onload="bodyload()">
<dl>
</dl>
</body>
</html>
Array
Object
Array of Objects
Embedded Object
FAQ: How to get the list of both properties and their type?
Ans: typeof operator
Ex:
<script>
fetch("http://fakestoreapi.com/products/1")
.then(function(response){
return response.json();
})
.then(function(product){
for(var property in product){
document.write(`${property} [${typeof product[property]}] => ${product[property]} <br>`);
}
})
</script>
EX:
<script>
fetch("http://fakestoreapi.com/products/1")
.then(function(response){
return response.json();
})
.then(function(product){
89
for(var property in product){
document.write(`${property} [${typeof product[property]}] => ${product[property]} <br>`);
}
document.write(`Is Stock property available in Product : ${"Stock" in product}`);
})
</script>
Ex:
<script>
fetch("http://fakestoreapi.com/products/1")
.then(function(response){
return response.json();
})
.then(function(product){
delete product.category;
delete product.rating;
for(var property in product){
document.write(`${property} [${typeof product[property]}] => ${product[property]} <br>`);
}
})
</script>
Map Type
- It is a key - value collection same like object.
- Key's can be any type.
- It provides implicit iterators and methods for reading and manipulation.
- It is faster in access.
- It is schema less. [Structure less]
Note: If you are dealing with structured data then use object, if it is schema less then use map
90
type.
Syntax:
var refName = new Map();
Ex:
<script>
var data = new Map();
data.set(1, "Samsung TV");
data.set("HTML", "Iti s a markup language");
document.write(data.get("HTML"));
</script>
Ex:
<script>
var data = new Map();
data.set(1, "Samsung TV");
data.set("HTML", "It is a markup language");
data.delete(1);
if(data.has(1)) {
document.write(data.get(1))
} else {
document.write(`There no key by name 1 <br>`);
}
document.write(`Total Number of Keys : ${data.size}<br>`);
for(var item of data.entries()){
document.write(item + "<br>");
}
</script>
Date Type
- Date type is defined by using JavaScript "Date()" constructor.
- It allocates memory for storing date type value.
- Date type is stored in "Year-Month-Day" format.
- It can handle both date and time values.
Syntax:
91
var mfd = new Date(); => loads the current system date and time
setHours()
setMinutes()
setSeconds()
setMilliSeconds()
setDate()
setMonth()
setYear()
EX:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-icons.css">
<script>
function GetTime(){
var now = new Date();
document.getElementById("time").innerHTML = now.toLocaleTimeString();
}
function bodyload(){
var weekdays = ["Sunday", "Monday", "Tuesday", "Wed","Thr","Friday","Saturday"];
var months = ["Jan", "Feb", "Mar", "April", "May", "June"];
92
msg.innerHTML = "Good Morning";
} else if (now.getHours()>12 && now.getHours()<=17) {
msg.innerHTML = "Good Afternoon";
} else {
msg.innerHTML = "Good Evening";
}
now.setMonth(2);
document.getElementById("cal").innerHTML = `${weekdays[now.getDay()]}
${now.getDate()} ${months[now.getMonth()]}, ${now.getFullYear()}`;
setInterval(GetTime, 1000);
}
</script>
</head>
<body class="container-fluid" onload="bodyload()">
<div class="btn-toolbar bg-danger justify-content-between">
<div class="btn-group">
<button class="btn btn-danger">Home</button>
<button class="btn btn-danger">About</button>
<button class="btn btn-danger">Contact</button>
</div>
<div class="btn-group">
<button class="btn btn-danger">
<span id="msg"> </span>
</button>
</div>
<div class="btn-group">
<button class="btn btn-danger">
<span class="bi bi-calendar" id="cal"></span>
</button>
<button class="btn btn-danger">
<span class="bi bi-clock" id="time"></span>
</button>
</div>
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function DateChange(){
var weekdays = ["Sunday", "Monday", "Tuesday", "Wed","Thr","Friday","Saturday"];
93
var months = ["Jan", "Feb", "Mar", "April", "May", "June"];
JavaScript Operators
- Operator is a object in computer programming that evaluates are value based on the operands.
- Operators are classified into various types based on the number of operands they can handle.
a+b => a, b are operands
x++, --y
x+y
94
- Ternary operator handles 3 operands
(condition)?true:false
one?two:three
- JavaScript operators are again classified into various groups based on the type of value they
return
1. Arithematic Operators
2. Comparision Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Special Operators
Arithematic Operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus Division
** Exponent [Math.pow()] New in ES5+ 2**3 = 8 => Math.pow(2,3)
++ Increment
-- Decrement
Increment
- Post
- Pre
var x = 10;
var y = x++; Post Increment x=x+1
x = 11, y=10
var x = 10;
var y = ++x; Pre Increment x=x+1
x = 11, y=11
Pre increment specifies that first increment is done and later it is assigned.
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script>
95
var count=0;
function ShowStatus(){
count++;
if(count==100){
location.href="shopper-template.html";
} else {
document.getElementById("status").innerHTML = count + " % ";
}
}
function LoadClick(){
document.getElementById("loading").style.display="block";
document.querySelector("button").style.display = "none";
setInterval(ShowStatus,200);
}
</script>
</head>
<body class="container-fluid">
<div class="d-flex justify-content-center align-items-center" style="height: 400px;">
<div>
<button onclick="LoadClick()" class="btn btn-primary">Load Template</button>
<div class="text-center" id="loading" style="display: none;">
<span class="spinner-border"></span>
<p id="status"></p>
<div>Loading</div>
</div>
</div>
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script>
var count=0;
function ShowStatus(){
count++;
document.getElementById("progress").value = count;
if(count==100){
location.href="shopper-template.html";
} else {
document.getElementById("status").innerHTML = count + " % ";
}
}
function LoadClick(){
96
document.getElementById("loading").style.display="block";
document.querySelector("button").style.display = "none";
setInterval(ShowStatus,200);
}
</script>
</head>
<body class="container-fluid">
<div class="d-flex justify-content-center align-items-center" style="height: 400px;">
<div>
<button onclick="LoadClick()" class="btn btn-primary">Load Template</button>
<div class="text-center" id="loading" style="display: none;">
<progress id="progress" min="1" max="100" value="1"></progress>
<p id="status"></p>
<div>Loading</div>
</div>
</div>
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-icons.css">
<script>
var id = 1;
function LoadProduct(){
id++;
fetch(`http://fakestoreapi.com/products/${id}`)
.then(function(res){
return res.json();
})
.then(function(product){
document.getElementById("title").innerHTML = product.title;
document.getElementById("poster").src = product.image;
document.getElementById("price").innerHTML = `₹ ${product.price}`;
})
}
function bodyload(){
LoadProduct();
}
function NextClick(){
id++;
LoadProduct();
97
}
function PrevClick(){
id--;
LoadProduct();
}
var timerMemory;
function PlayClick(){
timerMemory = setInterval(LoadProduct,5000);
document.getElementById("status").innerHTML = "(Slide Show - Started)";
}
function PauseClick(){
clearInterval(timerMemory);
document.getElementById("status").innerHTML = "(Slide Show - Paused)";
}
</script>
<style>
#price {
width: 120px;
height: 80px;
border: 1px solid black;
border-radius: 100px;
background-color: green;
color:white;
position: absolute;
top: 100px;
right: 150px;
padding: 20px;
text-align: center;
font-size: 20px;
}
</style>
</head>
<body class="container-fluid" onload="bodyload()">
<div id="price">
</div>
<div class="d-flex justify-content-center align-items-center" style="height: 500px;">
<div class="card w-50 p-2">
<div class="card-header text-center">
<p id="title"></p>
</div>
<div class="card-body">
<div class="row">
<div class="col-2 d-flex flex-column align-items-center">
<button class="btn btn-primary" onclick="PrevClick()">
<span class="bi bi-chevron-left"></span>
</button>
</div>
<div class="col-8 text-center">
<img id="poster" width="100%" height="300">
<h4 id="status"></h4>
98
</div>
<div class="col-2">
<button class="btn btn-primary" onclick="NextClick()">
<span class="bi bi-chevron-right"></span>
</button>
</div>
</div>
</div>
<div class="card-footer text-center">
<button class="btn btn-success" onclick="PlayClick()">
<span class="bi bi-play"></span>
</button>
<button class="btn btn-danger" onclick="PauseClick()">
<span class="bi bi-pause"></span>
</button>
</div>
</div>
</div>
</body>
</html>
Comparision Operators
> greater than
>= greater than or equal
< less than
<= less than or equal
== equal
=== identical equal
!= not equal
!== not identical
var x = "10";
var y = 10;
x = y; => assign
x == y; => true [converts and compares]
x === y; => false [true only when values are same type]
Ex:
<script>
var x = 10;
var y = "10";
document.write(`x(${typeof x})==y(${typeof y}) ? ` + (x==y) + "<br>");
document.write(`x(${typeof x})===y(${typeof y}) ? ` + (x===y) + "<br>");
</script>
99
Day 27 : JS Assignment & Conditional Operators – 05/04/23
Arithematic Operators
string + string ? string
string + number ? string
string + boolean ? string
number+number ? number
number+boolean ? number => 1 + true => 2
number+string ? string
Logical Operators
&& AND
|| OR
! NOT
Assignment Operators
+= Add and assign
-= sub and assign
/= divide and assign
*= multiply and assign
%= modulus and assign
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
100
<script>
var margin = 1;
function MoveClick(){
margin *= 2;
document.getElementById("pic").style.marginLeft = margin + "px";
}
function ClearClick(){
margin=1;
document.getElementById("pic").style.marginLeft = margin + "px";
}
</script>
</head>
<body>
<button onclick="MoveClick()">Move</button>
<button onclick="ClearClick()">Clear</button>
<div>
<img src="images/shoe.jpg" width="100" height="100" id="pic">
</div>
</body>
</html>
document.getElementsByTagName() [ ]
document.getElementsByName() [ ]
document.getElementsByClassName() [ ]
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var categoryName = "";
function SubmitClick(){
categoryName = "";
var categoryCheckBoxes = document.getElementsByName("Category");
for(var checkbox of categoryCheckBoxes){
if(checkbox.checked) {
categoryName += checkbox.value + "<br>";
}
}
document.querySelector("p").innerHTML = categoryName;
}
</script>
101
</head>
<body>
<h3>Categories</h3>
<ul style="list-style: none;">
<li><input type="checkbox" name="Category" value="Electronics"> Electronics</li>
<li><input type="checkbox" name="Category" value="Footwear"> Footwear</li>
<li><input type="checkbox" name="Category" value="Kids Fashion"> Kids Fashion</li>
<li><input type="checkbox" name="Category" value="Jewelery"> Jewelery </li>
</ul>
<button onclick="SubmitClick()">Submit</button>
<p></p>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var categoryName = "";
function CategoryChanged(){
categoryName = "";
var categoryCheckBoxes = document.getElementsByName("Category");
for(var checkbox of categoryCheckBoxes){
if(checkbox.checked) {
categoryName += checkbox.value + "<br>";
}
}
document.querySelector("p").innerHTML = categoryName;
}
</script>
</head>
<body>
<h3>Categories</h3>
<ul style="list-style: none;">
<li><input type="checkbox" onchange="CategoryChanged()" name="Category"
value="Electronics"> Electronics</li>
<li><input type="checkbox" onchange="CategoryChanged()" name="Category"
value="Footwear"> Footwear</li>
<li><input type="checkbox" onchange="CategoryChanged()" name="Category" value="Kids
Fashion"> Kids Fashion</li>
<li><input type="checkbox" onchange="CategoryChanged()" name="Category"
value="Jewelery"> Jewelery </li>
</ul>
<p></p>
</body>
102
</html>
Ex:
<script>
var products = [
{Name:"TV", Category:"Electronics"},
{Name:"Nike Casuals", Category:"Footwear"},
{Name:"Shirt", Category:"Fashion"},
{Name:"Watch", Category:"Electronics"}
];
var result = products.filter(function(product){
return product.Category=="Footwear" || product.Category=="Fashion";
})
for(var item of result) {
document.write(item.Name + "<br>");
}
</script>
Ex:
<script>
fetch("http://fakestoreapi.com/products")
.then(function(res){
return res.json();
})
.then(function(products){
var result = products.filter(function(product){
return product.category=="electronics" || product.category=="jewelery";
});
for(var item of result) {
document.write(item.title + "-" + item.category + "<br>");
}
})
</script>
104
Day 29 : If Select and Switch – 07/04/23
Selection Statements
- IF Select
a) Forward Jump
b) Simple Decision
Syntax:
if (condition1)
{
if(condition2) {
statement when all conditions evaluate to true;
}
else {
statement if condition 2 is false;
}
}
else
{
statement if condition-1 false;
}
Summary:
- If many conditions are available for test.
- There is a order for testing conditions
- Have to display individual errors messages of every condition
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var userDetails = {
"UserName": "john_nit",
"Password": "john@123"
}
function LoginClick(){
var username = document.getElementById("txtName").value;
var password = document.getElementById("txtPwd").value;
105
var error = document.querySelector("p");
if(username===userDetails.UserName)
{
if(password===userDetails.Password){
document.write("Login Success");
} else {
error.innerHTML = "Invalid Password".fontcolor('red');
}
} else {
error.innerHTML = "Invalid User Name".fontcolor('red');
}
}
</script>
</head>
<body>
<dl>
<dt>User Name</dt>
<dd><input type="text" id="txtName"></dd>
<dt>Password</dt>
<dd><input type="password" id="txtPwd"></dd>
</dl>
<button onclick="LoginClick()">Login</button>
<p align="center"></p>
</body>
</html>
d) Multiple Choices
- It is a decision making approache where we provide multiple choices for handling a specific
task.
- User can choose any one out of multiple choices.
- It must continue to with the selected choice.
Syntax:
if (choice-1)
{
statement on choice1;
}
else if(choice-2)
{
statement on choice2;
}
else if(choice-3)
{
statement on choice3;
}
else
{
statement when it is not among the given choices
}
106
Ex: Amazon Login
data/user.json
{
"Email": "[email protected]",
"Mobile": "+919876543210",
"Password": "john@123"
}
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Amazon Login</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script>
var flag = "";
function ContinueClick(){
var userid = document.getElementById("txtUserId").value;
var userError = document.getElementById("userError");
var userContainer = document.getElementById("userContainer");
var passwordContainer = document.getElementById("passwordContainer");
function ToggleContainers(){
userContainer.style.display = "none";
passwordContainer.style.display = "block";
}
fetch("../data/user.json")
.then(function(res){
return res.json();
})
.then(function(user){
if(userid===user.Email) {
flag = `Login Success and verification code sent to your registered email ${userid}`;
ToggleContainers();
} else if(userid===user.Mobile) {
flag = `Login Success and OTP sent to registered mobile ${userid}`;
ToggleContainers();
} else {
userError.innerHTML = `${userid} doesn't exist`;
}
107
})
}
function LoginClick(){
var password = document.getElementById("txtPwd").value;
fetch("../data/user.json")
.then(function(res){
return res.json();
})
.then(function(user){
if(user.Password===password) {
document.write(`<h2>${flag}</h2>`);
} else {
document.getElementById("pwdError").innerHTML = "Invalid Password";
}
})
}
</script>
</head>
<body class="container-fluid">
<div class="d-flex justify-content-center align-items-center" style="height:500px">
<div class="w-25">
<h2>SignIn</h2>
<div id="userContainer">
<div class="mb-3">
<label class="form-label fw-bold">Email or mobile phone number</label>
<div>
<input type="text" id="txtUserId" class="form-control">
<div class="text-danger" id="userError"></div>
</div>
</div>
<div>
<button onclick="ContinueClick()" class="btn btn-warning w-100">Continue</button>
</div>
</div>
<div id="passwordContainer" style="display:none">
<div class="mb-3">
<label class="form-label fw-bold">Password</label>
<div>
<input type="password" id="txtPwd" class="form-control">
<div id="pwdError" class="text-danger"></div>
</div>
</div>
<div>
<button class="btn btn-warning w-100" onclick="LoginClick()">Login</button>
</div>
</div>
</div>
</div>
</body>
</html>
108
FAQ: What is issue with multiple choices?
Ans: Compiler can't choose directly the condition, which is matching. It have to verify all
conditions until the specified is true.
Switch Selector
Syntax:
switch(value)
{
case value1:
statement;
jump_statement;
case value2:
statement;
jump_statement;
default:
statement if any value is not matching;
jump_statement;
}
Ex:
<script>
var n = parseInt(prompt("Enter Number"));
switch(n)
{
case 1:
document.write("One");
break;
case 2:
document.write("Two");
break;
case 3:
document.write("Three");
break;
case 4:
document.write("Four");
break;
default:
document.write("Please Enter 1 to 4 only");
break;
}
</script>
109
Day 30 : Conditional Programs Test – 08/04/23
1. Write a program to find if the given number is with in the specified range ?
Ex:
<script>
function FindRange(n, min, max) {
if(n>=min && n<=max) {
document.write(`Your number ${n} is in range of ${min} - ${max}`);
} else {
document.write(`Your number ${n} is out of range ${min} - ${max}`);
}
}
FindRange(14, 10, 20);
</script>
function FindLargest(a, b, c) {
FindLargest(10, 5, 19);
Ex:
<script>
function FindLargest(a,b,c){
if(a>b && a>c) {
document.write("A is Large");
} else if (b>c) {
document.write("B is Greater");
} else {
document.write("C is Greater");
}
}
FindLargest(10,34, 64);
</script>
3. Write a program to find if the given values are for a triangle or square?
110
function FindShape(values)
{
}
FindShape([100, 200, 50]); => It is a triangle
FindShape([10, 20, 40, 50]); => It is a square
Ex:
<script>
function FindShape(values){
if(values.length==3) {
document.write("Values are for Triangle");
} else if (values.length==4) {
document.write("values are for Square");
} else {
document.write("Please provide values only for square or triangle");
}
}
FindShape([10,40,20,20, 20]);
</script>
function FindEvenOdd(number)
{
if(number % 2 == 0)
{
even;
} else {
odd;
}
}
111
6. Write to program to Check if a triangle is equilateral, scalene, or isoscele s
7. Write a program to find the x,y values are in origin or in which quadrant.
Syntax:
switch(value)
{
case value:
statement;
jump_statement;
default:
statement;
jump_statement;
}
Ex:
<script>
var n = parseInt(prompt("Enter Number"));
switch(n)
{
case 1:
document.write("One");
break;
case 2:
112
document.write("Two");
break;
case 3:
document.write("Three");
break;
default:
document.write("Please Enter value between 1 to 3 only");
break;
}
</script>
FAQ's:
1. Can we define switch without default?
A. Yes.
<script>
function f1(){
var n = prompt("Your choice", "y/n");
switch(n)
{
case "y":
document.write("You Selected Yes");
break;
case "n":
document.write("You Selected No.");
break;
default:
document.write("Please enter y or n");
break;
}
}
113
f1();
</script>
<script>
function f1(){
var n = prompt("Your choice", "y/n");
switch(n)
{
case "y":
case "Y":
document.write("You Selected Yes");
break;
case "n":
case "N":
document.write("You Selected No.");
break;
default:
document.write("Please enter y or n");
break;
}
}
f1();
</script>
Ex:
<script>
function f1(){
var n = prompt("Your choice", "yes/no");
switch(n.toLowerCase())
{
case "yes":
document.write("You Selected Yes");
break;
case "no":
document.write("You Selected No.");
break;
default:
document.write("Please enter y or n");
break;
}
}
f1();
</script>
114
A. By using boolean expression in "case".
If case is using boolean expression, then switch value must be only "true".
EX:
<script>
function f1(){
var n = parseInt(prompt("Enter number"));
switch(true)
{
case (n>=1 && n<=10):
document.write(`your number ${n} is between 1 to 10`);
break;
case (n>10 && n<=20):
document.write(`Your number ${n} is between 11 to 20`);
break;
}
}
f1();
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var categories = ["Select Category", "Electronics", "Footwear"];
var electronics = ["Select Electronics", "Televisions", "Mobiles"];
var footwear = ["Select Footwear", "Casuals", "Boots"];
var products = [];
function LoadCategories(){
115
for(var category of categories)
{
var option = document.createElement("option");
option.text = category;
option.value = category;
document.getElementById("lstCategories").appendChild(option);
}
}
function LoadProducts(){
document.getElementById("lstProducts").innerHTML = "";
for(var product of products)
{
var option = document.createElement("option");
option.text = product;
option.value = product;
document.getElementById("lstProducts").appendChild(option);
}
}
function bodyload(){
LoadCategories();
}
function CategoryChanged(){
var categoryName = document.getElementById("lstCategories").value;
switch(categoryName){
case "Electronics":
products = electronics;
LoadProducts();
break;
case "Footwear":
products = footwear;
LoadProducts();
break;
default:
products = ["Please Select Category"];
LoadProducts();
break;
}
}
</script>
</head>
<body onload="bodyload()">
<dl>
<dt>Select Category</dt>
<dd><select id="lstCategories" onchange="CategoryChanged()"></select></dd>
<dt>Select Product</dt>
<dd><select id="lstProducts"></select></dd>
</dl>
</body>
</html>
116
Day 32 : Loops – 11/04/23
Looping Control Statements
- Looping is the process of executing a set of statements repeatedly until the given condition is
satisfied.
- Every loop contains
a) Initialization
b) Condition
c) Counter
- Loops are created by using
a) for
b) while
c) do while
Syntax:
for(initialization; condition; counter)
{
}
Ex:
<script>
for(var i=10; i>=1; i=i-1){
document.write(i + "<br>");
}
</script>
<script>
for(var i=1; i<=10; i++){
document.write(i + "<br>");
}
</script>
Ex:
<script>
var names = [];
for(var i=0;i<=9;i++){
var name = prompt(`Enter Name[${i+1}]`);
names[i] = name;
}
document.write(names);
</script>
- You can initialize and check for condition explicitly outside the for(), but the memory allocation
must be defined.
117
Syntax:
for( ; ; i++) // valid
{
}
Ex:
<script>
var names = [];
var i=0;
for( ;i<=9;i++){
var name = prompt(`Enter Name[${i+1}]`);
names[i] = name;
}
document.write(names);
</script>
Ex:
<script>
var menu = [
{Category: "Electronics", Products: ["Televisions", "Mobiles"]},
{Category: "Footwear", Products: ["Boots", "Casuals"]}
];
function bodyload(){
for(var i=0; i<menu.length; i++){
var li = document.createElement("li");
li.innerHTML = menu[i].Category;
for(var j=0; j<menu[i].Products.length;j++){
var ul = document.createElement("ul");
var ulLi = document.createElement("li");
ulLi.innerHTML = menu[i].Products[j];
ul.appendChild(ulLi);
li.appendChild(ul);
document.querySelector("ol").appendChild(li);
}
}
}
</script>
<body onload="bodyload()">
<ol>
</ol>
</body>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
118
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var topics = ["Web Technologies", "Front-End", "HTML", "Semantics", "Layout", "Header"];
function bodyload(){
for(var i=0; i<topics.length; i++){
var h = document.createElement(`h${i+1}`);
h.innerHTML = topics[i];
document.getElementById("container").appendChild(h);
}
}
</script>
</head>
<body onload="bodyload()">
<div id="container">
</div>
</body>
</html>
Syntax:
var i=0;
while(i<10)
{
i++;
console.log(i);
}
3. Do While
- It is similar to while loop but it ensures that the statements will execute at least once even when
the condition is false.
Syntax:
do
{
}while(condition);
Ex:
<script>
var i = 10;
do
{
i++;
document.write(i + "<br>");
}while(i<10);
</script>
119
Task:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var userDetails = {
UserName: "john",
Pin: 4535
}
function SubmitClick(){
var count = 0;
var pin = parseInt(document.getElementById("pin").value);
if(userDetails.Pin==pin){
document.write("PIN Verified Successfully..");
} else {
count++;
do {
document.write(`Invalid Pin - ${3-count} Attempts left`);
}while(count<=3)
}
}
</script>
</head>
<body>
<fieldset>
<legend>Verify PIN</legend>
<div>
Your PIN : <input type="text" id="pin"> <button onclick="SubmitClick()">Submit</button >
</div>
<p aling="center" id="error"></p>
</fieldset>
</body>
</html>
do {
count++;
document.querySelector("p").innerHTML = `${(3-count)} left`;
if(count==3){
document.querySelector("p").innerHTML="Card Blocked";
document.querySelector("button").disabled= true;
break;
}
} while(count>=3);
}
}
</script>
</head>
<body>
<fieldset>
<legend>Verify PIN</legend>
<div>
Your PIN : <input type="text" id="pin"> <button onclick="SubmitClick()">Submit</button >
</div>
<p aling="center" id="error"></p>
</fieldset>
</body>
</html>
Ex:
<script>
var values = [[10, 20, 90], [30,40], [50, 60, 80, 100], [120]];
for(var i=0; i<values.length; i++)
{
for(j=0; j<values[i].length; j++){
document.write(values[i][j] + " ");
}
121
document.write("<br>");
}
</script>
Iteration Statements
- Iteration is the process of reading elements from a collection in seqential order .
- It doesn't require initialization, condition and counter.
- Iterations can be created by using
Syntax:
for(var item of collection)
{
}
Jump Statements
a) break
b) return
c) continue
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function VerifyUserId(){
var userid = document.getElementById("txtUserId").value;
var userError = document.getElementById("UserError");
fetch("../data/users.json")
.then(function(res){
return res.json();
})
.then(function(users){
for(var user of users){
if(user.UserId==userid){
userError.innerHTML = "User Id Taken - Try Another".fontcolor('red');
break;
} else {
userError.innerHTML = "User Id Available".fontcolor('green');
}
}
})
122
}
</script>
</head>
<body>
<fieldset>
<legend>Register User</legend>
<dl>
<dt>User Id</dt>
<dd><input type="text" onkeyup="VerifyUserId()" id="txtUserId"></dd>
<dd id="UserError"></dd>
</dl>
</fieldset>
</body>
</html>
Ex:
<script>
function PrintNumbers(){
var stopNumber = parseInt(prompt("Loop Print 1 to 20 Set your Stop Number : ")) ;
- Continue is a jump statement, which skips the current context and continue to next .
Ex:
<script>
for(var i = 1; i<=20; i++) {
if(i==4 || i==14) {
continue;
}
document.write(i + "<br>");
123
</script>
Ex:
<script>
var products = [
{Name:"TV", Category:"Electronics"},
{Name:"Nike Casuals", Category:"Footwear"},
{Name:"Mobile", Category:"Electronics"},
{Name:"Shirt", Category:"Fashion"},
{Name:"Boots", Category:"Footwear"}
];
for(var item of products){
if(item.Category=="Fashion" || item.Category=="Electronics") {
continue;
}
document.write(item.Name + "<br>");
}
</script>
- Compile time errors are syntactical errors, due to which program fails to compile and start .
- Run time errors are the issues that occur at the time of using application.
your application is unable to understand to instructions given.
- If any application is unable to process the instructions given by user at runtime, then it leads to
"abnormal termination". [application closes]
- If application unable to understand instructions then exception will trigger, which leads to
abnormal termination.
Ex:
<script>
try {
var a = parseInt(prompt("Enter A value"));
124
var b = parseInt(prompt("Enter B value"));
if(b==0){
throw "Can't divide by Zero";
}
if(b>a) {
throw "Number too large..";
}
var c = a / b;
document.write(`Division = ${c}<br>`);
}
catch(ex) {
document.write(ex);
}
finally {
alert("Program End");
}
</script>
Functions in JavaScript
Ex:
1. Add a new JS file
"demo.js"
Function Configuration
- JavaScript function can be configured by using 2 techniques
125
a) function declaration
b) function expression
Declaration Syntax:
function Name(params)
{
}
Expression Syntax:
- Declaration allocates memory for a function, which is not accessible to another function .
- Expression allocates memory which can be share to multiple functions.
Ex:
<script>
var msg = prompt("Enter Message","hello | welcome");
var fun;
if(msg=="hello") {
fun = function(){
document.write("Hello ! JavaScript");
}
} else {
fun = function(){
alert("Welcome to Javascript");
}
}
fun();
</script>
Function Structure
- Every javascript function comprises of 3 basic elements
a) Declaration
b) Signature
c) Definition
Syntax:
function Print(msg)
{
}
126
- A function signature is used to access the function from any location.
Ex:
<script>
function PrintNumbers()
{
for(var i=1; i<=10; i++){
document.write(i + "<br>");
}
}
PrintNumbers();
PrintNumbers();
</script>
Function Parameters:
- A function parameter is required to modify the function.
- A function can change its functionality according to state and situation.
- Parameter is used for changing the functionality.
- Every function have parameters configure as
a) Formal Parameter
b) Actual Parameter
Syntax:
function Print(msg) => msg is formal parameter
{ It is just a memory allocated to store value
}
Formal_Parameter = Actual_Parameter;
Ex:
<script>
function PrintNumbers(howMany)
{
for(var i=1; i<=howMany; i++){
document.write(i + "<br>");
127
}
}
PrintNumbers(9);
</script>
Ex:
<script>
function VerifyValue(value)
{
document.write(`Your value ${value} is : ${typeof value}<br>`);
}
VerifyValue("Hello");
VerifyValue(30);
VerifyValue(true);
VerifyValue(["TV", "Mobile"]);
VerifyValue({Name:"TV", Price:4500});
VerifyValue(function(){document.write("Welcome");});
</script>
Ex:
<script>
function Demo(collection){
for(var item of collection){
document.write(item + "<br>");
}
}
Demo("Welcome");
</script>
Syntax:
function Name(param1, param2, ...)
{
}
Ex:
<script>
function Product(id, name, price){
if(id==undefined){
document.write(`
128
Name : ${name} <br>
Price : ${price}
`);
} else {
document.write(`
Id : ${id} <br>
Name : ${name} <br>
Price : ${price}
`);
}
}
Product(1,"TV", 34000.33);
</script>
function Name(param) {
}
Name(function(){})
Ans: It is used to handle various functionalities according to state and situation. A function can
change according to state and situation.
Note: When you define a function as parameter then it is not configured with "name".
Name(function(){})
129
Ex:
<script>
function VerifyPassword(password,success,failure){
if(password=="admin"){
success();
} else {
failure();
}
}
VerifyPassword("admin",function(){
document.write("Login Success");
}, function(){
document.write("Invalid Password");
})
</script>
Rest Parameters
=============
Syntax:
function Name(...paramName)
{
}
Ex:
<script>
function Product(...details)
{
var [id, name, price, stock] = details;
document.write(`
Id : ${id} <br>
Name : ${name} <br>
Price : ${price} <br>
Stock : ${stock}
`);
130
}
Product(1, "TV", 34000.33, true);
</script>
Ex:
<script>
function Product(title,...details)
{
var [id, name, price, stock] = details;
document.write(`
<h2>${title}</h2>
Id : ${id} <br>
Name : ${name} <br>
Price : ${price} <br>
Stock : ${stock}
`);
}
Product("Product Details",1, "TV", 34000.33, true);
</script>
Spread Syntax
============
- It is the process of configuring one actual parameter with multiple values, which can spread into
multiple formal parameters.
Syntax:
function Name(param1, param2, param3)
{
}
Ex:
<script>
function PrintDetails(id, name, price, stock){
document.write(`
Id : ${id} <br>
Name : ${name} <br>
Price : ${price} <br>
Stock : ${stock}
`);
}
131
var values = [1,"Samsung TV",45000.33,true];
PrintDetails(...values);
</script>
Ex:
<script>
function PrintCollection(a, b, c , d)
{
document.write(`
A = ${a} <br>
B = ${b} <br>
C = ${c} <br>
D = ${d}
`);
}
var data = [10, 20, 30];
PrintCollection(...data, 40);
</script>
function Name()
{
function Name()
{
return value;
}
Name = value;
- You can keep the memory of a function available even after the function ends.
- If there is no "return" it is void type, which removes the memory allocated for function .
132
- It is a mechanism of creating function which can use its own memory instead of accessing any
global memory.
- These type of functions are known as "Pure Functions"
Ex: Impure
<script>
var c = 0;
function Addition(a, b){
c = a + b;
}
function Result(){
document.write(`Addition = ${c}`);
}
Addition(10, 20);
Result();
</script>
Ex: Pure
<script>
function Addition(a, b){
return a + b;
}
function Result(){
document.write(`Addition = ${Addition(10,30)}`);
}
Result();
</script>
Ex:
<script>
133
function Template(template){
if(template=="login"){
return `
<h2>User Login </h2>
<dl>
<dt>User Id</dt>
<dd><input type="text"></dd>
<dt>Password</dt>
<dd><input type="password"></dd>
</dl>
<button> Login </button>
`;
} else {
return `
<h2>Register User </h2>
<dl>
<dt>User Id</dt>
<dd><input type="text"></dd>
<dt>Password</dt>
<dd><input type="password"></dd>
<dt>Email</dt>
<dd><input type="email"></dd>
<dt>Age</dt>
<dd><input type="number"></dd>
</dl>
<button> Login </button>
`;
}
}
function TemplateChange(){
var template = document.querySelector("select").value;
if(template=="login") {
document.querySelector("p").innerHTML = Template(template);
} else {
document.querySelector("p").innerHTML = Template(template);
}
}
</script>
<body>
<select onchange="TemplateChange()">
<option>Select Template</option>
<option value="login">Login</option>
<option value="register">Register</option>
</select>
<p></p>
</body>
134
Day 37 : JS Functions continued… – 17/04/23
Function Parameter
spread : one actual parameter can spread values to multiple formal
parameter.
rest : one formal parameter can accept multiple values as actual
parameter.
Function Return
pure with return
impure without return
Anonymous Functions
Syntax:
function() {
...some functionality...
}
Syntax:
(function(){
})();
Ex:
<script>
(function(){
document.write("Anonymous Function");
})();
</script>
Function Recursion
- It is the process of accessing a function with in the context of same function.
Syntax:
function f1()
{
f1();
}
135
- It is used for creating batch operations.
FAQ: Write a function without using loops and iterations to print numbers from 1 to 10.
function PrintNumber(n) {
Ex:
<script>
function PrintNumber(n){
document.write(n + "<br>");
n++;
if(n>10){
return;
}
PrintNumber(n);
}
PrintNumber(1);
</script>
function Factorial(n)
{
}
Factorial(5)
5 * 4 * 3 * 2 * 1 = 120
Ex:
<script>
function Fact(n){
if(n<1) {
return 1;
}
return n * Fact(n-1);
}
document.write(Fact(6));
</script>
Arrow Functions
() function parameters
=> return / single statement to execute
136
{} multiple statements to execute
Ex:
function hello() {
document.write("Hello ! JS");
}
Ex:
function hello(uname)
{
document.write(`Hello ! ${uname}`);
}
Ex:
function Addition(a, b)
{
return a + b;
}
Ex:
<script>
var hello = uname => `Hello ! ${uname}`;
document.write(hello("John"));
</script>
Ex:
<script>
fetch(`http://fakestoreapi.com/products`)
.then(response=> response.json())
.then(products=> {
products.map(product=> document.write(`<p>${product.title}</p>`))
})
</script>
Function Closure
- Closure is a technique where inner function can access the value of outer function .
137
- It is not just about inner function, any outer variable accessed inside a function is known as
"Closure".
Syntax:
<script>
var x =10;
function Print(){
console.log(x);
}
</script>
Ex:
<script>
function Outer()
{
var x = 10;
function Inner(){
document.write(`x=${x}`);
}
Inner();
}
Outer();
</script>
Ex:
<script>
function Outer()
{
var x = 10;
function Inner(){
var y = 20;
return `x=${x} y=20`;
}
var result = Inner();
document.write(result);
}
Outer();
</script>
Ex:
<script>
function Outer(outerValue){
return function Inner(innerValue){
return `Outer: ${outerValue} Inner : ${innerValue}`;
}
}
var result = Outer('Outer Value');
document.write(result('Inner Value'));
138
</script>
Syntax:
Outer("outerValue")("innerValue");
Ex:
<script>
function Outer(outerValue){
return function Inner(innerValue){
return `Outer: ${outerValue} <br> Inner : ${innerValue}`;
}
}
document.write(Outer("Outer function Value")("Inner function Value"))
</script>
Function Generator
Syntax:
function* Name()
{
}
Ex:
<script>
function* Demo(){
yield 1;
139
yield 2;
yield 3;
}
var obj = Demo();
document.write(`Value:${obj.next().value}<br>`);
document.write(`Value:${obj.next().value}<br>`);
document.write(`Value:${obj.next().value}<br>`);
</script>
Ex:
<script>
function* Demo(){
yield function(a,b){return a+b};
yield function(a,b){return a-b};
yield function(a,b){return a*b};
}
var obj = Demo();
console.log(obj.next().value(10,20));
console.log(obj.next().value(20,10));
console.log(obj.next().value(2,5));
</script>
Ex:
<script>
function* Demo(){
yield function(a,b){return a+b};
yield function(a,b){return a-b};
yield function(a,b){return a*b};
}
var obj = Demo();
console.log(obj.next().value(10,20));
console.log(obj.next().value(20,10));
obj.return();
console.log(obj.next().value(2,5)); // error-not defined
</script>
Ex:
<script>
function* Demo(){
let x = 1;
while(true){
let increment = yield x;
if(increment!=null) {
x+=increment;
} else {
x++;
}
}
}
140
var obj = Demo();
console.log(obj.next());
console.log(obj.next());
console.log(obj.next(10));
console.log(obj.next());
console.log(obj.next());
</script>
JavaScript OOP
- JavaScript is not an OOP language.
- It supports only few features of OOP.
- Various programming systems are used in software development
a) POPS
b) OBPS
c) OOPS
POPS
- Process Oriented Programming System
- It supports low level features.
- It can directly interact with hardware services.
- It uses less memory.
- It is faster.
EX: C, Pascal
- Code resuability issues
- Code separation issues
- Code extensibility issues
- Dynamic memory allocation issues.
OBPS:
- Object Based Programming System
- Provides reusability
- Supports separation and extensibility
- Supports dynamic memory allocations
Ex: JavaScript, VB
141
- No code level security
- No dynamic polymorphism
- No templates [Abstract members]
- No contracts [Interfaces]
OOPS
- Object Oriented Programming System
- Code reusability
- Code separation
- Code extensibility
- Easy testablility
- Code level security
- Supports dynamic polymorphism
- Provides templates and contracts
Evolution of OOP
- 1967 SIMULA - first OOP - Johan Olay , Nygaard - Code Resusability
- 1970's Small Talk - Trygve - Code Separation [MVC]
- 1975's C++
- 1990 Java
- 2003 C#
Modules in OOP
- JavaScript module is a set of functions and classes.
- Modules are used to build a library for application.
- So that you can import and reuse the library.
- Module system will not work of every device.
- You have to install a module system or use any browser, which is using a module system .
- There are different types of module systems
a) Common JS
b) UMD [Universal Module Distribution]
c) AMD [Asyncrhonous Module Distribution]
d) ECMA Module System
142
Ex:
1. Add a new folder into project by name "library"
2. Add subfolder "modules"
3. Add a new file into modules by name
home.module.js
function PrintName() {
Ex:
home.module.js
products.module.js
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
143
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module">
import {PrintName, Addition} from "../library/modules/home.module.js";
import {GetProducts} from "../library/modules/products.module.js";
</ol>
</body>
</html>
Ex:
home.module.js
index.html
144
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module">
import Addition,{PrintName} from "../library/modules/home.module.js";
import {GetProducts} from "../library/modules/products.module.js";
</ol>
</body>
</html>
Syntax:
import * as refObj from "../moduleName.js"
refObj.functionName()
refObj.className
Ex:
home.module.js
145
export function PrintName(){
return `Hello ! ${userName}`;
}
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module">
</script>
</head>
<body>
<p></p>
</body>
</html>
Class in OOP
- Class is a program template with data and logic, which you can customize and implement
according to the requirements.
- Class is known as a Model or Entity.
- Class refers to a logical entity where all the data and logic is defined.
- You can access the logic and data by using "Instance" of class.
- Class is a template that implements business or data.
- If a class is mapping to business requirements then it is called as "Entity".
- If a class is mapping to data requirements then it is called as "Model".
- It have the behaviour of blue-print, which is a prototype.
- Blue-Print is a source from where various instances are created.
Summary
- Class is Template
- Maps to Business => Entity
- Maps to Data => Model
- Prototype => Blue Print
Configuring class:
146
- You can configure a class in JavaScript by using 2 techniques
a) Class Declaration
b) Class Expression
Syntax: Declaration
class className
{
// members
}
Syntax: Expression
Ex:
<script>
var prototype = "Employee";
var memory = class {
// employee details
}
if(prototype=="Employee"){
memory = class {
//employee details
}
} else {
memory = class {
//student details
}
}
</script>
Class Members:
- A JavaScript class can have only
a) Property
b) Accessor
c) Method
d) Constructor
as class members.
147
Ans: Variables are immutable types. And class member can't be
immutable as class is a template.
Property
Syntax:
class Product
{
Price= 4500.44;
}
Syntax:
<script>
class Product
{
ProductId = 1;
Name = "Samsung TV";
Stock = true;
Cities = ["Delhi", "Hyd"];
Rating = {Rate:4.3, Count:3520}
}
</script>
Ex:
<script>
class Product
{
ProductId = 1;
Name = "Samsung TV";
Stock = true;
Cities = ["Delhi", "Hyd"];
Rating = {Rate:4.3, Count:3520}
}
148
var tv = new Product;
tv.Name = prompt("Enter Name");
document.write(`
Id : ${tv.ProductId} <br>
Name : ${tv.Name} <br>
Stock : ${tv.Stock} <br>
Cities : ${tv.Cities.toString()} <br>
Rating : Rate=${tv.Rating.Rate} Count=${tv.Rating.Count}
`);
</script>
- You can have fine control over property and change according to state and situation by using
"accessors"
Accessors
- Accessor gives a fine grained control over the property.
- It is used to handle read and write operations on property.
- Accessors are 2 types
a) Getter => get()
b) Setter => set()
PropertyName;
get aliasName() {
return this.PropertyName;
}
PropertyName;
149
set aliasName(newValue) {
this.PropertyName = newValue;
}
Ex:
1. Add a new file into modules
product.module.js
_productName;
get ProductName(){
return this._productName;
}
set ProductName(newName) {
if(this.Role=="admin") {
this._productName = newName;
} else {
this.Error = `Hello ! ${this.UserName} your role ${this.Role} is not authorized to set product
name`;
}
}
}
2. Page home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module">
import { Product } from "../library/modules/product.module.js";
var obj = new Product();
obj.UserName = prompt("Enter User Name");
obj.Role = prompt("Enter your Role");
obj.ProductName = prompt("Enter Product Name");
if(obj.ProductName){
document.querySelector("p").innerHTML = `Product Name : ${obj.ProductName}`;
} else {
150
document.querySelector("p").innerHTML = obj.Error;
}
</script>
</head>
<body>
<p></p>
</body>
</html>
Note: You can't configure event handler in HTML page and access in module. You have to define
events for elements in HTML page by using
"addEventListener()"
Syntax:
document.querySelect("button").addEventListener("eventName", functionName);
document.querySelect("button").addEventListener("click", DetailsClick);
Ex:
product.module.js
Home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module">
function DetailsClick(){
var obj = new Product();
obj.Name = prompt("Enter Name");
obj.Price = prompt("Enter Price");
obj.Stock = prompt("Enter Stock");
document.querySelector("p").innerHTML = `
Name = ${obj.Name} <br>
Price = ${obj.Price} <br>
Stock = ${obj.Stock}
`
}
151
document.getElementById("btnDetails").addEventListener("click", DetailsClick);
</script>
</head>
<body>
<button id="btnDetails">Get Details</button>
<p></p>
</body>
</html>
Ex: home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module">
import {Product} from "../library/modules/product.module.js";
function DetailsClick(){
var obj = new Product();
obj.Name = document.getElementById("Name").value;
obj.Price = document.getElementById("Price").value;
obj.Stock = (document.getElementById("Stock").checked==true)?"Available":"Out of Stock";
document.querySelector("p").innerHTML = `
Name = ${obj.Name} <br>
Price = ${obj.Price} <br>
Stock = ${obj.Stock}
`
}
document.getElementById("btnDetails").addEventListener("click", DetailsClick);
</script>
</head>
<body>
<dl>
<dt>Product Name</dt>
<dd><input type="text" id="Name"></dd>
<dt>Price</dt>
<dd><input type="text" id="Price"></dd>
<dt>Stock</dt>
<dd><input type="checkbox" id="Stock">Yes</dd>
</dl>
<button id="btnDetails">Get Details</button>
<p></p>
</body>
</html>
- You can also create an accessor to access any element from a hierarchy of elements.
152
get aliasName()
{
return this.Parent.Child.innerChild ;
}
Ex:
product.module.js
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module">
import {Product} from "../library/modules/product.module.js";
function DetailsClick(){
var obj = new Product();
obj.Name = document.getElementById("Name").value;
obj.Price = document.getElementById("Price").value;
obj.Stock = (document.getElementById("Stock").checked==true)?"Available":"Out of Stock";
document.querySelector("p").innerHTML = `
Name = ${obj.Name} <br>
Price = ${obj.Price} <br>
Stock = ${obj.Stock} <br>
Customer Rating = ${obj.CustomerRating}
`
}
document.getElementById("btnDetails").addEventListener("click", DetailsClick);
</script>
153
</head>
<body>
<dl>
<dt>Product Name</dt>
<dd><input type="text" id="Name"></dd>
<dt>Price</dt>
<dd><input type="text" id="Price"></dd>
<dt>Stock</dt>
<dd><input type="checkbox" id="Stock">Yes</dd>
</dl>
<button id="btnDetails">Get Details</button>
<p></p>
</body>
</html>
Syntax:
class ClassName
{
method() {
}
}
- The methods are accessed within class by using "this" and outside
class by using instance of class.
Ex:
export class Product
{
Details = "";
Name = "";
Price = 0;
Qty = 0;
Total(){
return this.Qty * this.Price;
}
Print(){
return this.Details =
`Name=${this.Name}<br>Price=${this.Price}<br>Qty=${this.Qty}<br>Total=${this.Total()}` ;
}
}
EX
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module">
import { Product } from "../library/modules/product.module.js";
var obj = new Product();
obj.Name = prompt("Enter name");
obj.Price = parseFloat(prompt("Enter Price"));
obj.Qty = parseInt(prompt("Enter Quantity"));
document.querySelector("p").innerHTML = obj.Print();
</script>
</head>
<body>
<p></p>
</body>
</html>
Ex:
<script>
class Product
{
Print(...args) {
for(var value of args){
document.write(value + "<br>");
}
}
}
let obj = new Product();
155
obj.Print(1, "TV", 45000.44, true);
</script>
Constructor
- Constructor is a special type of sub-route used for Instantiaton.
- Constructor is a design pattern used to create an object for class.
- Every class have a default constructor.
- It is used to for creating an object for class.
- JavaScript constructor is anonymous.
Syntax:
class Product
{
constructor() {
}
}
- If you want any action to be performed at the time of creating an object for class then you can
define by using constructor.
Ex:
<script>
class Database{
constructor(){
document.write(`Constructor Executed`);
}
}
let obj = new Database();
</script>
Ex:
<script>
class Database{
constructor(name){
document.write(`Hello ! ${name}`);
}
}
let obj = new Database("john");
</script>
Ex:
<!DOCTYPE html>
<html lang="en">
156
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
class Database
{
constructor(dbName){
document.write(`Connected with ${dbName} database..<br>`);
}
Insert(){
document.write(`Record Inserted`);
}
Delete(){
document.write(`Record Deleted`);
}
}
function InsertClick(){
var obj = new Database(document.getElementById("lstDatabase").value);
obj.Insert();
}
function DeleteClick(){
var obj = new Database(document.getElementById("lstDatabase").value);
obj.Delete();
}
</script>
</head>
<body>
<select id="lstDatabase">
<option>Choose Database</option>
<option>Oracle</option>
<option>MySql</option>
<option>MongoDB</option>
</select>
<button onclick="InsertClick()">Insert</button>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
class Database
157
{
ConnectionStatus = true;
constructor(dbName){
if(this.ConnectionStatus==true){
document.write(`Connected with ${dbName} database..<br>`);
} else {
document.write(`Invalid - Operation Please Connect to database`);
}
}
Insert(){
document.write(`Record Inserted`);
}
Delete(){
document.write(`Record Deleted`);
}
}
function InsertClick(){
var obj = new Database(document.getElementById("lstDatabase").value);
if(this.ConnectionStatus){
obj.Insert();
}
}
function DeleteClick(){
var obj = new Database(document.getElementById("lstDatabase").value);
if(this.ConnectionStatus){
obj.Delete();
}
}
</script>
</head>
<body>
<select id="lstDatabase">
<option>Choose Database</option>
<option>Oracle</option>
<option>MySql</option>
<option>MongoDB</option>
</select>
<button onclick="InsertClick()">Insert</button>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>
158
b) Inheritance
- You can extend the class with new features by using aggregation, which is object -to-object
communication.
- Aggregation is the process of creating an object for existing class in newly created class.
Without configuring relation between classes you can access the members of one class in
another class.
Ex:
<script>
class HDFC_Bank_Version1
{
Personal = "Personal Banking Services";
NRI = "NRI Banking Services";
Print(){
document.write(`${this.Personal}<br>${this.NRI}<br>`);
}
}
class HDFC_Bank_Version2
{
Loans = "Car and Personal Loans";
Print(){
let obj = new HDFC_Bank_Version1();
obj.Print();
document.write(`${this.Loans}`);
}
}
function InstallClick(){
var ver = document.querySelector("select").value;
switch(ver){
case "ver1":
document.write("<h2>HDFC Version-1</h2>");
let obj1 = new HDFC_Bank_Version1();
obj1.Print();
break;
case "ver2":
document.write("<h2>HDFC Version-2</h2>");
let obj2 = new HDFC_Bank_Version2();
obj2.Print();
break;
default:
document.write("Please Select a Version");
break;
}
}
</script>
<body>
<h2>Install Bank App </h2>
<select>
159
<option>Choose Version</option>
<option value="ver1">Version-1</option>
<option value="ver2">Version-2</option>
</select>
<button onclick="InstallClick()">Install</button>
</body>
Inheritance
- You can configure relation between classes.
- JavaScript uses "extends" keyword, to extend the existing class and add new features.
Syntax:
class A
{
}
class B extends A
{
Syntax:
super.member => property | method
super() => constructor
Ex: Inheritance
<script>
class HDFC_Bank_Version1
{
Personal = "Personal Banking Services";
NRI = "NRI Banking Services";
Print(){
document.write(`${this.Personal}<br>${this.NRI}<br>`);
}
}
class HDFC_Bank_Version2 extends HDFC_Bank_Version1
{
Loans = "Car and Personal Loans";
160
Print(){
super.Print();
document.write(`${this.Loans}`);
}
}
function InstallClick(){
var ver = document.querySelector("select").value;
switch(ver){
case "ver1":
document.write("<h2>HDFC Version-1</h2>");
let obj1 = new HDFC_Bank_Version1();
obj1.Print();
break;
case "ver2":
document.write("<h2>HDFC Version-2</h2>");
let obj2 = new HDFC_Bank_Version2();
obj2.Print();
break;
default:
document.write("Please Select a Version");
break;
}
}
</script>
<body>
<h2>Install Bank App </h2>
<select>
<option>Choose Version</option>
<option value="ver1">Version-1</option>
<option value="ver2">Version-2</option>
</select>
<button onclick="InstallClick()">Install</button>
</body>
Note: OOP inheritance Rule => If you configure relation between classes then you can access the
members of base class using derived class object. The rule is, you have to invoke the base class
constructor first, then followed by derived class constructor.
Syntax:
class Super
{
constructor() { }
}
class Derived extends Super
{
constructor() { } ==> invalid
}
161
Ex:
<script>
class SuperClass
{
constructor(){
document.write("Super Class Constructor<br>");
}
}
class DerivedClass extends SuperClass
{
constructor(){
super();
document.write("Derived Class Constructor");
}
}
let obj = new DerivedClass();
</script>
a) Single Inheritance
b) Multi Level Inheritance
Single Inheritance:
- A super class is extended by using Derived class.
- One super class and one derived class.
Ex:
<script>
class HDFC_Bank_Version1
{
Personal = "Personal Banking Services";
NRI = "NRI Banking Services";
Print(){
document.write(`${this.Personal}<br>${this.NRI}<br>`);
}
}
class HDFC_Bank_Version2 extends HDFC_Bank_Version1
{
Loans = "Car and Personal Loans<br>";
Print(){
super.Print();
document.write(`${this.Loans}`);
}
}
162
class HDFC_Bank_Version3 extends HDFC_Bank_Version2
{
AGRI = "Govt. Schemes";
Print(){
super.Print();
document.write(`${this.AGRI}`);
}
}
function InstallClick(){
var ver = document.querySelector("select").value;
switch(ver){
case "ver1":
document.write("<h2>HDFC Version-1</h2>");
let obj1 = new HDFC_Bank_Version1();
obj1.Print();
break;
case "ver2":
document.write("<h2>HDFC Version-2</h2>");
let obj2 = new HDFC_Bank_Version2();
obj2.Print();
break;
case "ver3":
document.write("<h2>HDFC Version-3</h2>");
let obj3 = new HDFC_Bank_Version3();
obj3.Print();
break;
default:
document.write("Please Select a Version");
break;
}
}
</script>
<body>
<h2>Install Bank App </h2>
<select>
<option>Choose Version</option>
<option value="ver1">Version-1</option>
<option value="ver2">Version-2</option>
<option value="ver3">Version-3</option>
</select>
<button onclick="InstallClick()">Install</button>
</body>
Note: OOP language will not support multiple inheritance for classes.
Reason : "Constructor Deadlock".
Syntax:
class Derived extends Super1, Super2, Super3.. =>invalid
163
{
Noe:
If same name methods are defined in classes that use inheritnace, then the derived class
members will hide the super class members.
You can access the hidden members of super class by using "super" keyword.
Polymorphism
- Poly means "Many"
- Morphos means "Forms"
- The ability of a component to work for various situations is polymorphism.
Ex:
<script>
class Employee
{
FirstName;
LastName;
Designation;
Print(){
document.write(`${this.FirstName} ${this.LastName} - ${this.Designation}<br>`);
}
}
class Developer extends Employee
{
FirstName = "Raj";
LastName = "Kumar";
Designation = "Developer";
Role = "Developer Role : Build, Debug, Test, Deploy";
Print(){
super.Print();
document.write(`${this.Role}`);
}
}
class Admin extends Employee
{
FirstName = "Kiran";
LastName = "Rao";
Designation = "Admin";
Role = "Admin Role : Authorizations";
Print(){
super.Print();
document.write(`${this.Role}`);
}
}
class Manager extends Employee
{
164
FirstName = "Tom";
LastName = "Hanks";
Designation = "Manager";
Role = "Manager Role : Approvals";
Print(){
super.Print();
document.write(`${this.Role}`);
}
}
let employees = new Array(new Developer(), new Admin(), new Manager());
let designation = prompt("Enter Designation");
for(var employee of employees){
if(employee.Designation===designation){
employee.Print();
}
}
</script>
window
- It provides properties and methods that are used to control the browser window.
Members:
prompt() : It popup an input box.
alert() : It popup an message box
open() : It can popup any file with specified features
close() : It can close the window
print() : It can invoke the printer properties.
Syntax:
window.open("path", "title", "features");
Ex:
<!DOCTYPE html>
165
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="window.open('images/m1.jpg','Mobile','width=300
height=400')">Open</button>
<button onclick="window.close()">Close</button>
<button onclick="window.print()">Print</button>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
@media screen {
tr:nth-child(even) {
background-color: lawngreen;
}
tr:nth-child(odd) {
background-color: aquamarine;
}
th {
background-color: green;
color:white;
}
}
@media print {
button {
display: none;
}
table {
background-color: lightgray;
}
}
</style>
</head>
<body>
<table border="1" width="400">
<caption>Products Table</caption>
<thead>
166
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Samsung TV</td>
<td>40000.33</td>
</tr>
<tr>
<td>Mobile</td>
<td>13000.33</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2" align="center">
<button onclick="window.print()">Print</button>
<br>
<span class="copyright"> © Copyright 2023</span>
</td>
</tr>
</tfoot>
</table>
</body>
</html>
location object
- It provides the properties and methods that are used to known the client location details .
Members:
host : It returns the server name or IP address.
protocol : It returns the protocol: http, https, file
port : It returns the port number
pathname : It returns the current file path
href : It gets and sets URL
search : It returns the query string
hash : It returns the current hash location.
Ex:
<script>
switch(location.protocol)
{
case "http:":
document.write(`
Host Name : ${location.host} <br>
Protocol : ${location.protocol} - You are using Live Server <br>
Port Number : ${location.port} <br>
Path : ${location.pathname} <br>
URL : ${location.href}
167
`);
break;
case "file:":
document.write(`
Protocol : ${location.protocol} - You are using File System <br>
Path : ${location.pathname} <br>
URL : ${location.href}
`);
}
</script>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function LoginClick(){
var username = document.getElementById("UserName").value;
var password = document.getElementById("Password").value;
if(username=="john" && password=="john@11"){
location.href= "shopper-template.html";
} else {
location.href= "error.html";
}
}
</script>
</head>
<body>
<dl>
<h2>User Login</h2>
<dt>User Name</dt>
<dd><input type="text" id="UserName"></dd>
<dt>Password</dt>
<dd><input type="password" id="Password"></dd>
</dl>
<button onclick="LoginClick()">Login</button>
</body>
</html>
EX: location.search
1. search.html
<!DOCTYPE html>
<html lang="en">
<head>
168
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search</title>
</head>
<body>
<form align="center" action="results.html">
<h1>Google</h1>
<input type="text" name="search" size="40">
<p>
<button>Search</button>
</p>
</form>
</body>
</html>
2. Results.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Results</title>
<script>
var topics = [
{Title: "HTML", Content:["HTML Semantics", "HTML Images", "HTML Links"]} ,
{Title: "JavaScript", Content: ["Variables", "Data Types", "Operators"]}
];
function bodyload(){
var queryString = location.search;
var searchString = queryString.substring(queryString.indexOf("=")+1);
topics.map(topic=>{
if(topic.Title==searchString){
topic.Content.map(item=>{
var li = document.createElement("li");
li.innerHTML = item;
document.querySelector("ol").appendChild(li);
})
}
})
}
</script>
</head>
<body onload="bodyload()">
<h3>Results</h3>
<ol>
169
</ol>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.topic {
width: 200px;
box-shadow: 2px 2px 2px black;
padding: 5px;
margin: 10px;
}
.container {
display: flex;
}
ul {
list-style: none;
display: flex;
margin-bottom: 50px;
}
li {
margin-right: 100px;
}
.topic:target {
background-color: black;
color:white;
}
</style>
170
<script>
function FetchClick(){
var topic = "";
var now = new Date();
switch(location.hash){
case "#html":
topic += "HTML Tutorial - " + now.toLocaleTimeString() + "<br>";
break;
case "#js":
topic += "JavaScript Basics - " + now.toLocaleTimeString() + "<br>";
break;
case "#css":
topic += "CSS Examples - " + now.toLocaleTimeString() + "<br>";
break;
case "#jq":
topic += "jQuery library - " + now.toLocaleTimeString() + "<br>";
break;
}
document.getElementById("topics").innerHTML += topic;
}
</script>
</head>
<body>
<ul>
<li><a href="#html">HTML</a></li>
<li><a href="#css">CSS</a></li>
<li><a href="#js">JavaScript</a></li>
<li><a href="#jq">jQuery</a></li>
</ul>
<div class="container">
<div class="topic" id="html">
<h2>HTML</h2>
<p>It is a markup language.</p>
</div>
<div class="topic" id="css">
<h2>CSS</h2>
<p>It defines styles for HTML.</p>
</div>
<div class="topic" id="js">
<h2>JavaScript</h2>
<p>It is a language for DOM</p>
</div>
<div class="topic" id="jq">
<h2>jQuery</h2>
<p>It is a JS library</p>
</div>
</div>
<p>
<h3>Recently Viewed <button onclick="FetchClick()">Fetch</button></h3>
<p id="topics"></p>
</p>
171
</body>
</html>
location.reload()
- It can reload the current page.
Syntax:
<button onclick="location.reload()">
HTML:
<meta http-equiv="refresh" content="4">
Navigator Object
- It is used to access client browser details.
Members:
Ex:
<script>
document.write(`
Browser Family : ${navigator.appName} <br>
Browser Version: ${navigator.appVersion} <br>
Language : ${navigator.language} <br>
Platform : ${navigator.platform} <br>
Cookie : ${(navigator.cookieEnabled==true)?"Cookies Enabled":"Cookies Disabled"} <br>
`);
</script>
Ex:
<script>
for(var item of navigator.plugins)
{
document.write(item.name + "<br>");
}
</script>
Ex:
<script>
if(navigator.plugins['PDF Viewer']==undefined){
document.write(`PDF Viewer is not available`);
172
} else {
document.write(`PDF Viewer is Working`);
}
</script>
"text/javascript" .js
"text/css" .css
Ex:
<script>
for(var item of navigator.mimeTypes){
document.write(item.type + "<br>");
}
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function bodyload(){
navigator.geolocation.getCurrentPosition(function(position){
document.querySelector("p").innerHTML = `
Latitude : ${position.coords.latitude} <br>
Longitude : ${position.coords.longitude}
`;
})
}
</script>
</head>
173
<body onload="bodyload()">
<p></p>
</body>
</html>
history object
- It is used to access the current browsing history.
Members:
go('page.html')
go(1) forward
go(-1) backward
Ex:
<script>
document.write(`
Total Count of Page in Current History : ${history.length}
`);
</script>
<button onclick="history.back()">Back</button>
Syntax:
function InsertClick()
{
}
<button onclick="InsertClick()">
What is EventListner ?
document.querySelector("button").addEventListener = { }
It allows an element to configure the event dynamically.
Event Arguments:
- Every event handler have 2 default arguments
a) this
b) event
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function InsertClick(obj)
{
document.write(`
Button Id : ${obj.id} <br>
Button Name : ${obj.name} <br>
Class Name : ${obj.className}
`);
}
</script>
</head>
<body>
<button id="btnInsert" name="Insert" class="btn btn-primary"
onclick="InsertClick(this)">Insert</button>
</body>
</html>
175
<button onclick="InsertClick(this.id)"> only ID is sent
<button onclick="InsertClick(this)"> all properties of button are sent
<button onclick="InsertClick(this.id, this.name,..)>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function InsertClick(e)
{
document.write(`
X Position : ${e.clientX} <br>
Ctrl Key : ${e.ctrlKey}
`);
}
</script>
</head>
<body>
<button id="btnInsert" name="Insert" class="btn btn-primary"
onclick="InsertClick(event)">Insert</button>
</body>
</html>
Syntax:
<button onclick="InsertClick(event)"> all details
<button onclick="InsertClick(event.altKey)"> specific
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function InsertClick(e, obj)
{
document.write(`
X Position : ${e.clientX} <br>
Ctrl Key : ${e.ctrlKey} <br>
Id : ${obj.id} <br>
Name : ${obj.name}
`);
}
176
</script>
</head>
<body>
<button id="btnInsert" name="Insert" class="btn btn-primary" onclick="InsertClick(event,
this)">Insert</button>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function InsertClick(msg)
{
document.write(`<h2>${msg}</h2>`);
}
</script>
</head>
<body>
<button onclick="InsertClick('Record Inserted')">Insert</button>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function InsertClick(obj, ...product)
{
var [id, name, stock, rating] = product;
document.write(`
Id: ${id} <br>
Name : ${name} <br>
Stock : ${stock} <br>
177
Rating : ${rating.rate} [${rating.count}] <br>
Button Id : ${obj.id}
`);
}
</script>
</head>
<body>
<button id="btnInsert" onclick="InsertClick(this, 1, 'Samsung TV', true, {rate:4.5,
count:3400})">Insert</button>
</body>
</html>
1. Mouse Events
2. Keyboard Events
3. Button Events
4. Form Events
5. Timer Events
6. Clipboard Events
7. Touch Events
8. Element State Events etc..
Mouse Events
- onmouseover
- onmouseout
- onmousedown
- onmouseup
- onmousemove
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function ShowDetails(){
document.querySelector("p").innerHTML = `
<b>Special Offer</b> <i> 50% OFF </i> on Nike Footwear.
`;
document.querySelector("img").style.width = "300px";
}
function HideDetails(){
document.querySelector("p").innerHTML = "";
document.querySelector("img").style.width = "100px";
}
178
</script>
</head>
<body>
<img onmouseover="ShowDetails()" onmouseout="HideDetails()" src="images/shoe.jpg"
width="100" height="100">
<p></p>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function ShowDetails(){
document.querySelector("p").innerHTML = `
<b>Special Offer</b> <i> 50% OFF </i> on Nike Footwear.
`;
}
function HideDetails(){
document.querySelector("p").innerHTML = "Hold down mouse button of Shoe to view
offer.";
}
</script>
</head>
<body>
<img onmousedown="ShowDetails()" onmouseup="HideDetails()" src="images/shoe.jpg"
width="100" height="100">
<p>Hold down mouse button of Shoe to view offer.</p>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
display: grid;
grid-template-columns: 2fr 10fr;
}
nav div {
179
border:1px solid blue;
padding: 2px;
width: 50px;
height: 50px;
margin-bottom: 20px;
}
nav div:hover {
cursor: grab;
}
</style>
<script>
function ImageHover(src){
document.getElementById("preview").src = src;
}
</script>
</head>
<body>
<nav>
<div>
<img onmouseover="ImageHover(this.src)" src="images/m1.jpg" width="50" height="50">
</div>
<div>
<img onmouseover="ImageHover(this.src)" src="images/m2.jpg" width="50" height="50">
</div>
<div>
<img onmouseover="ImageHover(this.src)" src="images/m3.jpg" width="50" height="50">
</div>
<div>
<img onmouseover="ImageHover(this.src)" src="images/m4.jpg" width="50" height="50">
</div>
<div>
<img onmouseover="ImageHover(this.src)" src="images/m5.jpg" width="50" height="50">
</div>
</nav>
<main>
<img id="preview" src="images/m1.jpg" width="300" height="400">
</main>
</body>
</html>
Ex:
180
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function GetPosition(x, y) {
var flag = document.querySelector("img");
flag.style.position = "fixed";
flag.style.left = x + "px";
flag.style.top = y + "px";
document.querySelector("div").innerHTML = `X=${x}px <br> Y=${y}px`;
}
</script>
</head>
<body onmousemove="GetPosition(event.clientX, event.clientY)">
<div style="height: 1000px;"></div>
<img src="images/flag.gif" width="50" height="50">
</body>
</html>
Keyboard Events
-onkeyup ] good to handle chars
-onkeydown ] It will not recognize the code until the char is finished
-onkeypress : It is good for handling keycodes.
Event Properties
keyCode
charCode
which
shiftKey
ctrlKey
altKey
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function VerifyUserId(userid){
var userError = document.getElementById("userError");
fetch("../data/users.json")
.then((res)=> {
return res.json();
181
})
.then(users=>{
for(var user of users){
if(user.UserId===userid){
userError.innerHTML = "User Id Taken - Try Another".fontcolor('red');
break;
} else {
userError.innerHTML = "User Id Available".fontcolor('green');
}
}
})
}
function VerifyCaps(e){
var pwdError = document.getElementById("pwdError");
console.log(e.keyCode + "\n" + e.which);
if(e.keyCode>=65 || e.which>=65 && e.keyCode<=90 || e.which<=90) {
pwdError.style.display = "block";
} else {
pwdError.style.display = "none";
}
}
</script>
</head>
<body>
<dl>
<h3>Register User</h3>
<dt>User Id</dt>
<dd><input type="text" onkeyup="VerifyUserId(this.value)" id="UserId"></dd>
<dd id="userError"></dd>
<dt>Password</dt>
<dd><input type="password" id="password" onkeypress="VerifyCaps(event)"></dd>
<dd id="pwdError" style="color:goldenrod; display: none;">
Warning : Caps is ON
</dd>
</dl>
</body>
</html>
Button Events
- onclick
- ondblclick
- oncontextmenu
- onselectstart => click and drag
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
182
<script>
document.oncontextmenu = function(){
alert(`Right Click not allowed`);
return false;
}
document.onselectstart = function(){
return false;
}
</script>
</head>
<body>
<h2>Right Click is disabled on this page.</h2>
<img src="images/m1.jpg" ondblclick="window.open('images/m1.jpg','Mobile','width=400
height=400')" width="50" height="50">
<p>double click to view large</p>
</body>
</html>
Keyboard Events
- onkeyup
- onkeydown
- onkeypress
Button Events
- onclick
- ondblclick
- oncontextmenu
- onselectstart
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
183
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function ShowTip(){
document.getElementById("msg").innerHTML = "Name in Block Letters Only";
}
function ChangeCase(){
document.getElementById("msg").innerHTML = "";
var username = document.getElementById("UserName").value;
document.getElementById("UserName").value = username.toUpperCase();
}
</script>
</head>
<body>
<dl>
<dt>Name</dt>
<dd><input type="text" onfocus="ShowTip()" onblur="ChangeCase()" id="UserName"></dd >
<dd id="msg"></dd>
</dl>
</body>
</html>
Form Events
- onsubmit : It defines the actions to perform when form submitted.
- onreset : It defines the actions to perform when form resets.
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form onsubmit="alert('form will submit its data to server')" onreset="alert('Your form will reset -
Data will erase')">
User Name :
<input type="text" name="UserName">
<button type="submit">Submit</button>
<button type="reset">Cancel</button>
</form>
</body>
</html>
184
FAQ: Can we submit form data to server on any other element event.
How to submit form on dropdown change.
[form can be submitted implicitly only by using submit button]
Syntax:
formName.submit();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function PostClick(){
frmLogin.submit();
}
function VerifyName(){
var username = document.getElementById("UserName").value;
if(username.length==4) {
document.getElementById("password").focus();
document.getElementById("UserName").disabled=true;
}
}
</script>
</head>
<body>
<form name="frmLogin" onsubmit="alert('form will submit its data to server')"
onreset="alert('Your form will reset- Data will erase')">
User Name :
<input type="text" onkeyup="VerifyName()" id="UserName" name="UserName">
Password:
<input type="password" name="Password" id="password">
<button type="submit">Submit</button>
<button type="reset">Cancel</button>
<button type="button" onclick="PostClick()">Post</button>
</form>
</body>
</html>
Clipboard Events:
- oncut
- oncopy
185
- onpaste
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function Cut(){
document.querySelector("p").innerHTML="Removed - Copied to clipboard";
}
function Copy(){
document.querySelector("p").innerHTML= "Copied to clipboard";
}
function Paste(){
document.querySelector("p").innerHTML = "Inserted from clipboard";
}
document.oncut = function(){
alert("Cut not allowed");
return false;
}
</script>
</head>
<body>
<textarea id="msg" oncut="Cut()" oncopy="Copy()" onpaste="Paste()" rows="4"
cols="40">Welcome to JavaScript Events</textarea>
<p></p>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
document.oncut = function(){
alert("Cut not allowed");
return false;
}
</script>
186
</head>
<body>
<textarea id="msg" oncut="Cut()" oncopy="Copy()" onpaste="Paste()" rows="4"
cols="40">Welcome to JavaScript Events</textarea>
<p></p>
</body>
</html>
Touch Events
- ontouchstart
- ontouchend
- ontouchmove
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function MoveImage(e){
var x = e.touches[0].clientX;
var y = e.touches[0].clientY;
var img = document.querySelector("img");
img.style.position = "fixed";
img.style.top = y + "px";
img.style.left = x + "px";
}
</script>
</head>
<body ontouchmove="MoveImage(event)">
<img src="../public/images/m1.jpg" width="200" height="300">
</body>
</html>
setTimeout()
- It loads the given function into memory and delays its execution by specified time interval .
Syntax:
187
setTimeout(function(){ }, timeInterval)
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function msg1(){
document.querySelector("h2").innerHTML = "Hello !";
}
function msg2(){
document.querySelector("h2").innerHTML = "How are you?";
}
function msg3(){
document.querySelector("h2").innerHTML = "Welcome to JavaScript";
}
var m1, m2, m3;
function bodyload(){
m1 = setTimeout(msg1, 3000);
m2 = setTimeout(msg2, 5000);
m3 = setTimeout(msg3, 10000);
}
function ClearMessage2(){
clearTimeout(m2);
}
</script>
</head>
<body onload="bodyload()">
<button onclick="ClearMessage2()">Clear Message 2</button>
<h2 align="center"></h2>
</body>
</html>
setInterval()
- It loads the task into memory and will release at regular time interval.
- It will repeat the task until removed from memory.
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interval</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<style>
188
body {
display: flex;
justify-content: center;
align-items: center;
height: 500px;
text-align: center;
}
</style>
<script>
function FetchClick(){
document.getElementById("buttonContainer").style.display = "none";
document.getElementById("statusContainer").style.display = "block";
setInterval(SetCount, 100);
}
var count = 0;
function SetCount(){
count++;
document.getElementById("count").innerHTML = `${count} % completed`;
if(count==100) {
document.getElementById("statusContainer").style.display = "none";
document.getElementById("imageContainer").style.display = "block";
}
}
</script>
</head>
<body >
<div>
<div id="buttonContainer">
<button onclick="FetchClick()" class="btn btn-primary">Fetch Image</button>
</div>
<div id="statusContainer" style="display: none;">
<span class="spinner-border"></span>
<div>Loading...
<p id="count"></p>
</div>
</div>
<div id="imageContainer" style="display: none;">
<img src="../public/images/m1.jpg" width="300" height="300">
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interval</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
189
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 500px;
text-align: center;
}
</style>
<script>
var timer;
function FetchClick(){
document.getElementById("buttonContainer").style.display = "none";
document.getElementById("statusContainer").style.display = "block";
timer = setInterval(SetCount, 100);
}
var count = 0;
function SetCount(){
count++;
document.getElementById("progress").value = count;
document.getElementById("count").innerHTML = `${count} % completed`;
if(count==100) {
document.getElementById("statusContainer").style.display = "none";
document.getElementById("imageContainer").style.display = "block";
}
}
function PauseClick(){
clearInterval(timer);
document.getElementById("count").innerHTML = `${count} % Paused`;
}
function ResumeClick(){
timer = setInterval(SetCount, 100);
document.getElementById("count").innerHTML = `${count} % Completed`;
}
</script>
</head>
<body >
<div>
<div id="buttonContainer">
<button onclick="FetchClick()" class="btn btn-primary">Fetch Image</button>
</div>
<div id="statusContainer" style="display: none;">
<progress id="progress" min="1" max="100" value="1"></progress>
<p id="count"></p>
<p>
<button onclick="ResumeClick()">></button>
<button onclick="PauseClick()">||</button>
</p>
</div>
</div>
<div id="imageContainer" style="display: none;">
190
<img src="../public/images/m1.jpg" width="300" height="300">
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Slide Show</title>
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-icons.css">
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script>
var count = 0;
function GetProduct(){
count++;
fetch(`http://fakestoreapi.com/products/${count}`)
.then((response)=> {
return response.json();
})
.then((product)=>{
console.log(product);
document.getElementById("title").innerHTML = product.title;
document.getElementById("pic").src = product.image;
})
}
function bodyload(){
GetProduct();
}
var show;
function PlayClick(){
show = setInterval(GetProduct, 5000);
document.getElementById("status").innerHTML = "Slide Show Started";
}
function PauseClick(){
clearInterval(show);
document.getElementById("status").innerHTML = "Slide Show - Paused";
}
</script>
</head>
<body onload="bodyload()" class="container-fluid d-flex justify-content-center">
<div class="mt-2 card w-50">
<div class="card-header text-center">
191
<p id="title"></p>
<p id="status"></p>
</div>
<div class="card-body">
<img width="100%" height="300px" id="pic">
</div>
<div class="card-footer text-center">
<button class="btn btn-primary" onclick="PlayClick()">
<span class="bi bi-play"></span>
</button>
<button class="btn btn-danger" onclick="PauseClick()">
<span class="bi bi-pause"></span>
</button>
</div>
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container{
display: flex;
justify-content: center;
align-items: center;
height: 500px;
}
@keyframes zoomIn
{
from {
width: 30px;
height: 40px;
}
to {
width: 300px;
height: 400px;
}
}
</style>
<script>
function ZoomClick(){
var img = document.querySelector("img");
img.style.animationName = "zoomIn";
img.style.animationDuration = "5s";
192
img.style.animationIterationCount = "infinite";
}
</script>
</head>
<body>
<button onclick="ZoomClick()">Zoom</button>
<div class="container">
<div>
<img src="images/m1.jpg" width="300" height="400">
</div>
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Slide Show</title>
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-icons.css">
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script>
var count = 0;
function GetProduct(){
count++;
fetch(`http://fakestoreapi.com/products/${count}`)
.then((response)=> {
return response.json();
})
.then((product)=>{
console.log(product);
document.getElementById("title").innerHTML = product.title;
document.getElementById("pic").src = product.image;
})
}
function bodyload(){
GetProduct();
}
var show;
function PlayClick(){
show = setInterval(GetProduct, 5000);
document.getElementById("status").innerHTML = "Slide Show Started";
}
function PauseClick(){
clearInterval(show);
document.getElementById("status").innerHTML = "Slide Show - Paused";
}
193
function SetAnimation(){
var img = document.getElementById("pic");
img.style.animationName = "ZoomIn";
img.style.animationDuration = "5s";
}
</script>
<style>
@keyframes ZoomIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
</style>
</head>
<body onload="bodyload()" class="container-fluid d-flex justify-content-center">
<div class="mt-2 card w-50">
<div class="card-header text-center">
<p id="title"></p>
<p id="status"></p>
</div>
<div class="card-body" style="height:300px">
<img width="100%" onload="SetAnimation()" height="250px" id="pic">
</div>
<div class="card-footer text-center">
<button class="btn btn-primary" onclick="PlayClick()">
<span class="bi bi-play"></span>
</button>
<button class="btn btn-danger" onclick="PauseClick()">
<span class="bi bi-pause"></span>
</button>
</div>
</div>
</body>
</html>
Summary of Events
1. mouse
2. keyboard
3. button
4. clipboard
5. form
6. element state
7. touch
8. timer
194
Ans : By use "createElement()" method of document object.
document.createElement("button");
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event</title>
<script>
function bodyload(){
var button = document.createElement("button");
button.innerHTML = "Dynamic Button";
document.querySelector(".container").appendChild(button);
button.addEventListener("click", function(){
alert(`Dynamic Button Clicked`);
})
}
</script>
</head>
<body onload="bodyload()">
<div class="container">
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event</title>
<script>
function bodyload(){
var label = document.createElement("label");
var input = document.createElement("input");
var button = document.createElement("button");
195
input.id = "txtPassword";
button.innerHTML = "Login";
button.addEventListener("click", function(){
if(input.value=="admin") {
document.write("Success");
} else {
document.write("Invalid");
}
})
}
</script>
</head>
<body onload="bodyload()">
<div class="container">
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event</title>
<script>
function bodyload(){
var label = document.createElement("label");
var input = document.createElement("input");
var button = document.createElement("button");
button.innerHTML = "Login";
196
button.addEventListener("click", function(e){
console.log(e.clientX);
if(input.value=="admin") {
document.write("Success");
} else {
document.write("Invalid");
}
})
}
</script>
</head>
<body onload="bodyload()">
<div class="container">
</div>
</body>
</html>
Syntax:
function Name(value, success, failure)
{
if(condition) {
success();
} else {
failure();
}
}
- Callback is synchronous.
- It will not move to next task until if finish the given task.
- It is slow in resolving the function.
Ex:
<script>
function FetchData(url, success, failure){
if(url=="http://fakestoreapi.com/products") {
success('Fetched Data Successfully..');
} else {
failure('Unable to fetch data');
}
197
}
FetchData(prompt("Enter URL"),
(msg)=>{
document.write(`Success: ${msg}`);
},
(msg)=>{
document.write(`Failure: ${msg}`);
}
)
</script>
Promise
- Promise is a proxy.
- A proxy defines about uncertenity in resolving the given issues.
- Promises comprises 3 states
var fs = require("fs");
console.log(`--Reading File---`);
console.log(data.toString());
console.log(`--Read Complete--`);
> read.js
var fs = require("fs");
198
}
});
console.log(`---Read Complete----`);
>node read.js
Syntax:
const name = new Promise(resolve, reject);
Ex:
<script>
var FetchData = new Promise((resolve, reject)=>{
var url = prompt("Enter URL");
if(url=="http://fakestoreapi.com/products"){
resolve('Fetched Data Successfully..');
} else {
reject('Unable to fetch data');
}
});
FetchData.then((msg)=>{
document.write(`Success: ${msg}`);
}).catch((msg)=>{
document.write(`Failure: ${msg}`);
})
</script>
Ex:
<script>
var GetProducts = new Promise((resolve)=>{
resolve('Gets all products');
});
var GetCategories = new Promise((resolve)=>{
resolve('Get all Categories list');
})
var GetCart = new Promise((resolve)=>{
resolve('Get Your Cart Details');
})
Promise.all([
199
GetProducts,
GetCategories,
GetCart
]);
Promise.race([
GetProducts,
GetCategories,
GetCart
])
</script>
Syntax:
Promise.all([
promise1,
promise2,
promise3
]).then(collection=>{
})
<script>
var GetProducts = new Promise((resolve)=>{
resolve('Gets all products');
});
var GetCategories = new Promise((resolve)=>{
resolve('Get all Categories list');
})
var GetCart = new Promise((resolve)=>{
resolve('Get Your Cart Details');
})
Promise.race([
GetProducts,
GetCategories,
GetCart
]).then(result=>{
console.log(result);
})
</script>
JavaScript Ajax
- User can stay on one page and can get access to everything on to page without reloading the
complete page.
Syntax:
201
var http = new XMLHttpRequest();
Member Description
-------------------------------------------------------------------------- -
onreadystatechange It defines a function to execute when ajax
state changes.
2xx Success
3xx Redirections
4xx Client Side Issues
5xx Server Side Issues
text/plain
application/pdf
application/xml
application/json
image/jpeg
Syntax:
open("GET", "URL", true) => true is async
202
send() It sends response to client.
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax</title>
<script>
var http = new XMLHttpRequest();
function GetEMI(){
http.open("GET", "emi.html", true);
http.send();
http.onreadystatechange = function() {
if(http.readyState==4) {
document.getElementById("container").innerHTML = http.responseText;
}
}
}
function GetNasa(){
http.open("GET", "slide-show.html", true);
http.send();
http.onreadystatechange = function() {
if(http.readyState==4) {
document.getElementById("container").innerHTML = http.responseText;
}
}
}
function bodyload(){
var now = new Date();
document.getElementById("status").innerHTML = now.toLocaleTimeString();
}
</script>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
</head>
<body class="container-fluid" onload="bodyload()">
<h3>Page Last Fetched : <span id="status"></span></h3>
<button onclick="GetEMI()">EMI Calculator</button>
<button onclick="GetNasa()">Slide Show</button>
<hr size="3" noshade color="red">
<div id="container">
</div>
</body>
</html>
203
Day 53 : JavaScript Request Types – 09/05/23
Response Type
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax</title>
<script>
var http = new XMLHttpRequest();
function HelpClick(){
http.open("get", "../data/help.txt");
http.send();
http.onreadystatechange = function(){
if(http.readyState==4) {
document.getElementById("container").innerHTML = http.responseText;
}
}
}
</script>
</head>
<body>
<button onclick="HelpClick()">Help</button>
<hr size="2" noshade>
<pre id="container"></pre>
</body>
</html>
Distributed Computing
204
- Web Service Specifications
a) SOAP
b) REST
c) JSON
SOAP
- Service Oriented Architecture Protocol
- Consumer sends XML request
- Provider sends XML response
REST
- Representational State Transfer
- Consumer sends query request
- Provider sends XML response, optionally JSON
JSON
- JavaScript Object Notation
- Consumer sends JSON request
- Provider sends JSON response.
parentNode
parentElement
childNodes
firstChild
lastChild
previousSibling
nextSibling
nodeValue
textContent
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax</title>
<script>
var http = new XMLHttpRequest();
function HelpClick(){
http.open("get", "../data/help.txt", true);
http.send();
http.onreadystatechange = function(){
205
if(http.readyState==4) {
document.getElementById("container").innerHTML = http.responseText;
}
}
}
function ProductsClick(){
http.open("get", "../data/products.json", true);
http.send();
http.onreadystatechange = function(){
if(http.readyState==4){
var data = JSON.parse(http.responseText);
for(var item of data){
var tr = document.createElement("tr");
var tdName = document.createElement("td");
var tdPrice = document.createElement("td");
tdName.innerHTML = item.Name;
tdPrice.innerHTML = item.Price;
tr.appendChild(tdName);
tr.appendChild(tdPrice);
document.querySelector("tbody").appendChild(tr);
}
}
}
}
function XMLClick(){
http.open("get", "../data/product.xml", true);
http.send()
http.onreadystatechange = function(){
let xmldoc = http.responseXML;
var root = xmldoc.querySelector("root");
document.getElementById("container").innerHTML = root.firstChild.data;
}
}
</script>
</head>
<body>
<button onclick="HelpClick()">Help-Text</button>
<button onclick="ProductsClick()">Products-JSON</button>
<button onclick="XMLClick()">XML Data</button>
<hr size="2" noshade>
<pre id="container"></pre>
<table border="1" width="300">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
206
<tbody>
</tbody>
</table>
</body>
</html>
- You also used "async and await" keywords for creating async functions.
- Modern JavaScript prefers using promise.
function Name(){
return Promise.resolve();
}
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
async function Welcome(){
let pro = new Promise((resolve, reject)=>{
resolve('Welcome to JavaScript Async');
});
document.querySelector("p").innerHTML = await pro;
}
function btnClick(){
Welcome();
}
</script>
</head>
<body>
<button onclick="btnClick()">Click</button>
<p></p>
</body>
</html>
207
Day 54 : JavaScript Data Structures – 10/05/23
JavaScript Data Structure and Algorithms
- Data Structure in computer programming defines how data is stored and manipulated, which
includes adding, removing, sorting, filtering etc.
1. Stack
2. Queue
3. Hash Table
4. Linked List
5. Tree - Binary Tree
6. Graph etc..
Stack
- It uses the mechanism LIFO. [Last-in-First Out]
- The last value added into collection will be the first value to read.
- Usually stack comprisess of methods
Ex:
stack.js
208
return this.length;
}
}
stack-demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module">
import { Stack } from "../library/ds/stack.js";
let collection = new Stack();
collection.push("A");
collection.push("B");
console.log(collection.size());
console.log(collection.pop());
console.log(collection.size());
console.log(collection.peek());
console.log(collection.size());
</script>
</head>
<body>
</body>
</html>
Queue
- It uses the mechanism FIFO
Methods:
enqueue() add new item
dequeue() remove return first item
size()
Ex:
queue.js
enqueue(value){
this.collection.push(value);
}
dequeue(){
209
return this.collection.shift();
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module">
import { Queue } from "../library/ds/queue.js";
let collection = new Queue();
collection.enqueue("A");
collection.enqueue("B");
collection.enqueue("C");
console.log(collection.dequeue());
</script>
</head>
<body>
</body>
</html>
Linked List
- Collection with nodes where the current node will invoke the next node.
Methods:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
210
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script type="module">
import { Queue } from "../library/ds/queue.js";
var tokens = new Queue();
var tokenNumber = 1;
var GenerateTokenButton = document.getElementById("btnGenerateToken");
function LoadTokens(){
document.getElementById("lstTokens").innerHTML="";
for(var item of tokens.collection){
var opt = document.createElement("option");
opt.text = item;
opt.value = item;
document.getElementById("lstTokens").appendChild(opt);
}
}
GenerateTokenButton.addEventListener("click",()=>{
var username = prompt("Enter Your Name");
tokens.enqueue(`${tokenNumber} [${username}]`);
tokenNumber++;
alert(`Token Generated`);
LoadTokens();
})
document.getElementById("btnCounter1").addEventListener("click",()=>{
document.getElementById("lstCounter1").innerHTML = "";
var opt = document.createElement("option");
opt.text = tokens.dequeue();
document.getElementById("lstCounter1").appendChild(opt);
if(tokens.size()==0) {
document.getElementById("lblCounter1").innerHTML = `No more Customers`;
} else {
document.getElementById("btnCounter2").addEventListener("click",()=>{
document.getElementById("lstCounter2").innerHTML = "";
var opt = document.createElement("option");
opt.text = tokens.dequeue();
speech.text = `Token ${opt.text} go to Counter Number 2`;
window.speechSynthesis.speak(speech);
document.getElementById("lstCounter2").appendChild(opt);
LoadTokens();
211
})
document.getElementById("btnCounter3").addEventListener("click",()=>{
document.getElementById("lstCounter3").innerHTML = "";
var opt = document.createElement("option");
opt.text = tokens.dequeue();
speech.text = `Token ${opt.text} go to Counter Number 3`;
window.speechSynthesis.speak(speech);
document.getElementById("lstCounter3").appendChild(opt);
LoadTokens();
})
document.getElementById("Counter1CheckBox").addEventListener("change",(e)=>{
if(e.target.checked){
document.getElementById("btnCounter1").disabled=false;
} else {
document.getElementById("btnCounter1").disabled=true;
}
})
document.getElementById("Counter2CheckBox").addEventListener("change",(e)=>{
if(e.target.checked){
document.getElementById("btnCounter2").disabled=false;
} else {
document.getElementById("btnCounter2").disabled=true;
}
})
document.getElementById("Counter3CheckBox").addEventListener("change",(e)=>{
if(e.target.checked){
document.getElementById("btnCounter3").disabled=false;
} else {
document.getElementById("btnCounter3").disabled=true;
}
})
</script>
</head>
<body class="container-fluid">
<div class="row mt-3">
<div class="col">
<h4>Counter-1 <span class="form-switch"><input type="checkbox" id="Counter1CheckBox"
class="form-check-input"></span> </h4>
<select id="lstCounter1" size="3" class="form-select">
</select>
<button id="btnCounter1" disabled class="btn mt-2 btn-success">Call Customer</button>
<label class="form-label mt-3 bg-dark text-white" id="lblCounter1"></label>
</div>
<div class="col">
<h4>Counter-2 <span class="form-switch"><input type="checkbox" id="Counter2CheckBox"
class="form-check-input"></span> </h4>
212
<select id="lstCounter2" size="3" class="form-select">
</select>
<button id="btnCounter2" disabled class="btn mt-2 btn-success">Call Customer</button>
<label class="form-label bg-dark text-white" id="lblCounter2"></label>
</div>
<div class="col">
<h4>Counter-3 <span class="form-switch"><input type="checkbox" id="Counter3CheckBox"
class="form-check-input"></span> </h4>
<select id="lstCounter3" size="3" class="form-select">
</select>
<button id="btnCounter3" disabled class="btn mt-2 btn-success">Call Customer</button>
<label class="form-label bg-dark text-white" id="lblCounter3"></label>
</div>
</div>
<div class="row text-center" style="margin-top: 200px;">
<div>
<select id="lstTokens" size="3" class="form-select" style="height: 100px;">
</select>
<button class="btn mt-2 btn-primary" id="btnGenerateToken">Generate Token</button>
</div>
</div>
</body>
</html>
- Algorithms define how your application perform when input size grows.
- Time taken to perform any task.
- Big O Notation
Linear - O(n)
Ex:
<script>
function PrintTotal(number)
{
var result = 0;
for(var i=1; i<=number; i++){
result = result + i;
}
return result;
}
let startProfiling = 0;
let endProfiling = 0;
startProfiling = performance.now();
document.write(PrintTotal(100000) + "<br>");
endProfiling = performance.now();
213
let totalProfileTime = endProfiling - startProfiling;
document.write("Total Time : " + totalProfileTime);
</script>
Constant - O(1)
Ex:
<script>
function PrintPow(number, p)
{
return Math.pow(number,p);
}
let startProfiling = 0;
let endProfiling = 0;
startProfiling = performance.now();
document.write(PrintPow(3,10) + "<br>");
endProfiling = performance.now();
let totalProfileTime = endProfiling - startProfiling;
document.write("Total Time : " + totalProfileTime);
</script>
Quad O(n2)
Cubic O(n3)
Ex:
<script>
function FetchData(){
let startProfiling = 0;
let endProfiling = 0;
startProfiling = performance.now();
fetch("http://fakestoreapi.com/products")
.then(res=>res.json())
.then(data=>{
FetchData();
</script>
Ex:
<script>
function FetchData(){
214
let startProfiling = 0;
let endProfiling = 0;
startProfiling = performance.now();
fetch("http://fakestoreapi.com/products")
.then(res=>res.json())
.then(data=>{
var result = data.filter(item=> item.category=="electronics");
result.map(product=>
document.write(`<li>${product.title}</li>`)
)
})
endProfiling = performance.now();
let totalProfileTime = endProfiling - startProfiling;
console.log(totalProfileTime);
}
FetchData();
</script>
Cookie:
- It is a simple text document, that comprises of client details.
- It is appended into browser memory or into client device [HDD]
Query String
- It transports data by appending it into URL of address bar.
?key=value
215
- It is visible to all users
- It is not safe
- It can be bookmarked
- It is stored in browser logs.
- We have a limit for data "2048chars"
- can't handle complex data like binary
location.search
Local Storage:
- JavaScript allows to store data locally in browser.
- window.localStorage is used to configure data in local storage.
- It will never expire.
- You have to manually remove local storage.
Syntax:
localStorage.setItem("key", value);
localStorage.getItem("key");
localStorage.removeItem("key");
localStorage.clear();
Ex:
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<script>
function LoginClick(){
var username = document.getElementById("UserName").value;
window.localStorage.setItem("username", username);
location.href = "home.html";
}
</script>
</head>
<body>
<h2>Login</h2>
User Name :
<input type="text" id="UserName"> <button onclick="LoginClick()">Login</button >
</body>
216
</html>
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
<script>
function bodyload(){
var user = window.localStorage.getItem("username");
if(user==null){
location.href="login.html";
} else {
document.querySelector("p").innerHTML=`Hello ! ${user}`;
}
}
function Signout(){
window.localStorage.removeItem("username");
location.href="login.html";
}
</script>
</head>
<body onload="bodyload()">
<h2>Home</h2>
<p></p>
<button onclick="Signout()">Signout</button>
</body>
</html>
Session Storage
- It is not permanent.
- It is removed when browser is closed.
- It is not accessible to another tab in same browser.
Ex:
login.html
<!DOCTYPE html>
<html lang="en">
217
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<script>
function LoginClick(){
var username = document.getElementById("UserName").value;
window.sessionStorage.setItem("username", username);
location.href = "home.html";
}
</script>
</head>
<body>
<h2>Login</h2>
User Name :
<input type="text" id="UserName"> <button onclick="LoginClick()">Login</button >
</body>
</html>
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
<script>
function bodyload(){
var user = window.sessionStorage.getItem("username");
if(user==null){
location.href="login.html";
} else {
document.querySelector("p").innerHTML=`Hello ! ${user}`;
}
}
function Signout(){
window.sessionStorage.removeItem("username");
location.href="login.html";
}
</script>
</head>
<body onload="bodyload()">
<h2>Home</h2>
<p></p>
<button onclick="Signout()">Signout</button>
</body>
</html>
218
Cookies
- It is a document object.
- Cookie is a simple text document where client details are stored.
- Cookie can be temporary or persistent.
- Temporary is in-memory which is remove when browser is claose.
- Persitent is permanent with expiry date.
- cookie data is accessible to server.
Ex:
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<script>
function LoginClick(){
var username = document.getElementById("UserName").value;
document.cookie = `UserName=${username}; expires=${new Date("2023-05-15
10:30:00AM")}`;
location.href = "home.html";
}
</script>
</head>
<body>
<h2>Login</h2>
User Name :
<input type="text" id="UserName"> <button onclick="LoginClick()">Login</button >
</body>
</html>
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
<script>
function bodyload(){
var user = document.cookie;
var [username] = user.split(';');
var result = username.substring(username.indexOf("=")+1);
document.querySelector("p").innerHTML= `Hello ! ${result}`;
}
function Signout(){
219
document.cookie="";
location.href="login.html";
}
</script>
</head>
<body onload="bodyload()">
<h2>Home</h2>
<p></p>
<button onclick="Signout()">Signout</button>
</body>
</html>
Web Components
- A component comprises of
a) Presentation
b) Logic
c) Styles
- Component enables reusability and extensibility.
- You can create custom elements and add to page.
- Presentation is defined by using HTML
- Styles are defined by using CSS
- Logic is defined by using JavaScript
- You can create custom components are you can use built-in components.
- There are also reffered as custom elements
- Custom Elements are 2 types
a) Standalone
b) Extended
- Standalone is creating a new HTML element manually and defining functionalit y
document.createElement("div");
Syntax:
class MyElement extends HTMLElement
{
constructor(){
super();
this.attributeName = value;
}
Syntax:
static get observedAttributes()
Syntax:
connectedCallBack()
{
let shadow = this.shadowRoot({mode: 'open | close'});
}
Syntax:
let shadow = this.attachShadow({ mode : 'open' });
shadow.innerHTML = `
<style> </style>
`
Ex:
<!DOCTYPE html>
221
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
class MyDialog extends HTMLElement
{
constructor(){
super();
this.caption = "some caption";
}
static get observedAttributes(){
return ['caption'];
}
attributeChangedCallback(property, oldValue, newValue) {
if(oldValue==newValue) {
return;
}
this[property] = newValue;
}
connectedCallback(){
let shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = `
<style>
h2 {
text-align: center;
font-family: 'Arial'
}
</style>
<h2>${this.caption}</h2>
`;
}
}
customElements.define("my-dialog", MyDialog);
</script>
<style>
my-dialog {
box-shadow: 2px 2px 2px gray;
border:1px solid red;
}
</style>
</head>
<body>
<h2>Custom Elements</h2>
222
</body>
</html>
Phases of Component
- Component is derived from "HtmlElement"
- Component is created using
constructor()
- Component constructor must call super constructor
- Component properties are defined in constructor
- Component properties are accessed by using
attributesChangedCallback() { }
connectedCallback() { }
attachShadow() { }
customComponent.define("tagName" , className)
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
class Login extends HTMLElement
{
constructor(){
super();
this.logintitle = "Some Title";
}
static get observedAttributes(){
223
return ['logintitle'];
}
attributeChangedCallback(property, oldValue, newValue){
if(oldValue===newValue) {
return;
}
this [property] = newValue;
}
connectedCallback(){
var shadow = this.attachShadow({mode:"open"});
shadow.innerHTML = `
<dl>
<h3>${this.logintitle}</h3>
<dt>User Name</dt>
<dd><input type="text"></dd>
<dt>Password</dt>
<dd><input type="password"></dd>
</dl>
<button>Login</button>
<button>Cancel</button>
`;
}
}
customElements.define("my-login", Login);
</script>
</head>
<body>
<my-login logintitle="Admin Login"></my-login>
<hr>
<my-login logintitle="User Login"></my-login>
</body>
</html>
jQuery
- It is a JavaScript library for building UI.
- Library provides pre-defined functions and components.
- jQuery introduced in 2006 by John Resig
- "Write Less - Do More"
<script>
$(function(){
224
... your jquery code...
})
</script>
(or)
<script>
$(document).ready(function(){
});
</script>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script>
$(function(){
$("h1").text("jQuery");
$("#subtitle").html(`<b><i>Write Less - Do More</i></b>`);
$(".txt").html("jQuery is a JavaScript library for building effective UI");
})
</script>
</head>
<body>
<h1></h1>
<p id="subtitle"></p>
<div class="txt"></div>
</body>
</html>
225
jQuery DOM Events
all JavaScript events are same
You have to use event listeners
$("button").click(function(event){
event.clientX
event.keyCode
event.target.id
event.target.name
event.target.className
})
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script>
$(function(){
$("button").click(()=>{
$("p").html(`Hello ! ${$("#UserName").val()}`);
})
})
</script>
</head>
<body>
Your Name : <input type="text" id="UserName"> <button>Submit</button>
<p></p>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script>
var categories = ["Electronics", "Footwear", "Fashion"];
$(function(){
226
categories.map((value)=>{
$(`<li>${value}</li>`).appendTo("ol");
$(`<option>${value}</option>`).appendTo("select");
})
})
</script>
</head>
<body>
<ol></ol>
<select></select>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script>
$(function(){
$.ajax({
method: "get",
url: "http://fakestoreapi.com/products",
success: (data)=>{
data.map((item)=>{
$(`<tr>
<td>${item.title}</td>
<td><img src=${item.image} width="100" height="100"></td>
<td>${item.price}</td>
</tr>`).appendTo("tbody");
})
}
})
})
</script>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
</head>
<body class="container-fluid">
<table class="table table-hover">
<thead>
<tr>
<th>Title</th>
<th>Image</th>
<th>Price</th>
</tr>
</thead>
227
<tbody>
</tbody>
</table>
</body>
</html>
jQuery UI
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="../node_modules/jquery-ui/jquery-ui.css">
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="../node_modules/jquery-ui/jquery-ui.js"></script>
<script>
$(function(){
$("#dept").datepicker();
})
</script>
</head>
<body>
Departure
<input type="text" id="dept">
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="../node_modules/jquery-ui/jquery-ui.css">
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="../node_modules/jquery-ui/jquery-ui.js"></script>
<script>
$(function(){
$("#faqs").accordion();
})
</script>
</head>
<body>
<div id="faqs">
<h2>What is Netflix?</h2>
228
<div>
<p>something about netflix</p>
</div>
<h2>How to access Netflix?</h2>
<div>
<p>something..</p>
</div>
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="../node_modules/jquery-ui/jquery-ui.css">
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="../node_modules/jquery-ui/jquery-ui.js"></script>
<script>
$(function(){
$("ol").sortable();
})
</script>
</head>
<body>
<ol>
<li>JavaScript</li>
<li>CSS</li>
<li>Bootstrap</li>
<li>HTML</li>
</ol>
</body>
</html>
https://drive.google.com/file/d/1O4qlxp9l5ULpxcJuqnkQZvFWPHt3TQtw/vie
w?usp=drive_web&authuser=0
229
230
231