JavaScript Programming Tutorial Notes Udemy
JavaScript Programming Tutorial Notes Udemy
Table of contents
Variables in JavaScript:
Data Types in JavaScript
JS: Numbers
JS In-Built Number Functions
JS String
JS In-Built String Functions part-1
JS In-Built String Functions part-2
Null and Undefined Values
Conditional Statements
if-else
Switch
Arithmetic Operators
Assignment Operators
Comparison and Logical Operators
JS Type Coercion
Implicit Type Coercion
Explicit Type Coercion
Objects and Array
Objects
Arrays Part 1
Arrays Part 2
JS Loops
While Loop
For Loop
Functions and Hoisting
Functions
Function Arguments
Scope and Environment
JS Hoisting- Variable Hoisting
JS Hoisting- Function Hoisting
Document Object Model (DOM)
Intro to DOM
Select HTML Elements
example:
JS Query Selector-string
JS Update HTML Elements
example 2
JS Updating Styles
JS Intro to Events
Add & Remove Classes from HTML using JS
Get Element style values using JS
Form Events
Keyboard Events
Mouse Events
JS - Create HTML elements - Part 1
JS - Create HTML elements - Part 2
JS - Update and Delete HTML Elements (Lec41)
Lec 41 Assignment TODO List web app
Browser Object Model (BOM)
Introduction to Browser Object model
Screen and Navigator Object
History and Location Object
JS Regular Expressions
Introduction to Regular Expressions
Meta-characters and Character Classes
Regex Quantifiers
Using Regex in JS
Regex Groups
The Problem:
The Solution
Form Validation using Regex
OOP in JavaScript
Introduction to OOP in JS
this keyword
Constructor Functions
Inheritancs and Prototype Chain
Prototype Implementation
JS HTTP Requests
Understanding Frontend and Backend
HTTP Requests and Responses
Introduction to JSON
Introduction to AJAX
Handling HTTP Response
Making HTTP Post Requests
jQuery
Introduction
Variables in JavaScript:
TOC
var , let , are keywords used to create variables
var and let are both used for variable declaration in JavaScript but the difference between them is that var is
function scoped and let is block scoped. It can be said that a variable declared with var is defined throughout the
program as compared to let.
Example of var:
**Input:**
console.log(x);
var x=5;
console.log(x);
**Output:**
undefined
5
Example of let:
**Input:**
console.log(x);
let x=5;
console.log(x);
**Output:**
ReferenceError : Cannot access 'x' before initializaiton
parseInt() will parse and return a Integer (11) and not a floating point number (11.5)
parseFloat() takes string number as i/p and returns a floating number
var StrNum1 = "10";
var StrNum2 = "11.5";
var StrNum3 = "abc";
console.log(parseFloat(StrNum1)); //10
console.log(parseFloat(StrNum2)); //11.5
console.log(parseFloat(StrNum3)); //NaN
JS String
TOC
var myFirstString = "I love JavaScript";//--double quote
console.log(typeOf(myFirstString)); //"string"
console.log(myFirstString.slice(-2)); //"JS"
/*here '-2' denotes the start and from that posotion till the end all chars will be
returned*/
console.log(myFirstString.slice(4));
//" is a JS string, something JS"
/*starting index = 4 ending index = -1*/
console.log(myFirstString.substr(10, 2));//"JS"
console.log(myFirstString.substr(10));
//"JS string, something JS"
/*if no length is mentioned then starting from index = 10, till the end all the
char will be returned*/
JS In-Built String Functions part-2
TOC
var ExampleString = "This is JS string funciton part2";
charAt() this take a position as an argument and returns the char at that position
var ExampleString = "this is JS";
console.log(charAtString.charAt(5)); //"i"
console.log(ExampleString.split());
//[ 'this is JS' ]
console.log(ExampleString.split(''));
null is a value that can be assigned to a variable to denote that it contains no value.
var myvar = null;
console.log(myvar);
Conditional Statements
if-else
TOC
if(7>5)
{
console.log("hello");
}
else if(7 == 5)
{
console.log("else part1");
}
else{
console.log("finally");
}
Switch
TOC
using if-else
var currentDay = 'Mon';
if(currentDay == "Mon")
{
console.log('timings: 10:00-6:00');
}
else if(currentDay == 'Wed')
{
console.log('timings: 9:30-5:00');
}
using switch-case
switch (currentDay) {
case 'Mon':
console.log('timings: 10:00-6:00');
break;
case 'Wed':
console.log('timings: 9:30-5:00');
break;
default:
console.log('no date matches');
break;
}
Arithmetic Operators
TOC
Addition : '+'
Subtraction : '-'
Multiplication : '*'
Division : '/'
Modulus : '%'
Increment : '++'
Decrement : '--'
!= is not equal to operator compares only value and doesn't compare the dataType
1.
2.
3.
4.
Implicit Type Coercion of conversion to boolean
anything that's not 0, null, undefined, empty will be converted to true
ex:
'apple', 1, 25, -5, etc. will be true
null, undefined, NaN, 0 and empty string '' or "" will be false
to number
to boolean
Objects and Array
Objects
TOC
Stores data in form of key,value pair
var cars = {
'p1': '320kmph',
'ferrari': '200kmph',
'benz' : '500kmph',
};
console.log(cars);
console.log(typeof(cars));
var mAgera = {
name : "Agera",
manufacturer : {
name: 'anc',
location: 'sweden'
},
topspeed: 429,
color: 'black',
spoilers: false,
applyBrakes: function(){
setTimeout(function(){
//after 5000millisec it will fire the callback funciton
console.log('Car Stopped');
}, 5000)
}
}
console.log(mAgera.name);
console.log(mAgera.manufacturer);
console.log(mAgera.topspeed);
console.log(mAgera.manufacturer.name);
console.log(mAgera.applyBrakes());
//note that it took 5 seconds for the funciton to return the o/p and it is done
Asynchronously as till that time the below line was executed
console.log(mAgera.applyBrakes);
//to call a funciton inside a object we need to use paranthesis or else it will
give us the defination of the function
Output:
Arrays Part 1
TOC
Arrays are special type of Objects
var MyFriends = ['aks', 'hk', 'sns', 'rv'];
console.log(MyFriends);
console.log(typeof(MyFriends));
console.log(MyFriends[0]);
console.log(MyFriends[3]);
// updaitng a value
MyFriends[0] = 'adarsh';
console.log(MyFriends);
console.log(MyFriends);
MyFriends[MyFriends.length] = 'as';
console.log(MyFriends);
// or else
MyFriends.push('us');
console.log(MyFriends);
// pop out the last value from the list and returns it
var last = MyFriends.pop();
console.log(MyFriends);
console.log(last);
Output:
Arrays Part 2
TOC
Adding and Deleting from an Array. using slice() method
var MyFriends = ['aks', 'hk', 'sns', 'rv', 'ss', 'as', 'us' ];
console.log(MyFriends);
console.log(typeof(MyFriends));
MyFriends.splice(0, 0, 'RedHat');
console.log(MyFriends);
MyFriends.splice(4, 1);
console.log(MyFriends);
MyFriends.splice(0, 2);
console.log(MyFriends);
Output:
JS Loops
Repetition of code is called loop and each repetition is called Iteration
While Loop
TOC
var mval = 0;
while (mval < 50) {
mval++
}
console.log(mval);// 50
For Loop
TOC
Simple for loop
Part 2
Functions and Hoisting
Functions
1.
2.
Function Arguments
TOC
If a default value is provided in the function parameter and no argument is passed while calling the function
then the default value is considered.
1.
2.
Note that JS will ignore the extra values if passed as Arguments.
Scope and Environment
Scope defines the part of the program where a Variable or a function is visible/accessible.
The Variable defined outside all the functions and blocks are available throughout the code. These are called
Global Variable.
var num1 = 10;// num1 is a Global Variable
function sum(num2) {
var total = num1 + num2;//total is a local Variable
console.log(total);//Local Scope of num1
}
console.log(num1);
//Global Scope of num1
console.log(total);
//ReferenceError: total is not defined
This mechanism in which functions and variable can be used before declaring them is known as Hoisting.
What happens in Hoisting is that the Variable and Function declarations move to the top of their scope before
the code execution.
JavaScript has two step in executing a particular Script.
1. Creation: Here JS analyses all the code and allocates the memory space for Variable and Function
2. Execution
All variable are assigned a value Undefined when declared first
console.log(x);
x = "Some-String";
console.log(x);
var x;
console.log(x);
// ReferenceError: x is not defined
x = "Some-String";
console.log(x);
// var x;
Hence the variable must be declared somewhere or else like this can occur
JS Hoisting- Function Hoisting
TOC
Moves the Function declarations to the top of the Scope, to make functions usable before declaring them. ex:
sum(1, 3);
sum(10, 3);
function sum(n1, n2)
{
console.log(n1+n2);
}
sum(20, 5);
Output:
Hoisting doesn't move the function expression to the top because it is treated as assignment and not
declaration
sum(1, 3);
sum(10, 3);
var sum = function(n1, n2)
{
console.log(n1+n2);
}
sum(20, 5);
Output:
TypeError: sum is not a function
The error occurred because JS treated sum as assignment and not as declaration
On Correction it works
// sum(1, 3);
// sum(10, 3);
var sum = function(n1, n2)
{
console.log(n1+n2);
}
sum(20, 5);
Output:
Which total will be printed in line 3 :- the Global Variable total or the Local Variable total
The best place to include script tag is to place it just before </body> so that the HTML document can get
properly loaded before the execution of JS.
we can use multiple JS files it doesn't have to be one.
HTML
JS
Browser Console
This is a DOM method and it accepts the HTML element id and returns the HTML element for the id.
if no element matches the id then returns null .
2.
getElementByClassName('html-class-string');
gebcn in short
It returns a JS Object.
methods like onClick() , onDrag() , etc.. are events which can be listened by JS.
3.
similar kind of method is document.getElementsByTagName()
It returns a JS Object based on the name of the tag passed as argument
example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS-notes</title>
<link rel="stylesheet" href = "./JS-notes.css" type="text/css"></link>
</head>
<body class="class1">
<nav id="navbar">
<ul>
<li>Home</li>
<li>Contact</li>
<li>Services</li>
<li>About Us</li>
</ul>
</nav>
<form action="input"></form>
#id1{
background-color: aquamarine;
border: 3px 4px 3px 4px;
border-style: solid;
padding: 15px;
margin: 50px;
}
#id2{
background-color: rgb(40, 207, 54);
border: 3px 4px 3px 4px;
border-style: solid;
padding: 15px;
margin: 50px;
}
#id3{
background-color: rgb(54, 33, 78);
border: 3px 4px 3px 4px;
border-style: solid;
padding: 15px;
margin: 50px;
}
#navbar
{
margin: 10px;
padding: 1px;
border: 3px solid crimson;
}
#navbar ul{
display: flex;
flex-direction: row;
justify-content: center;
}
#navbar ul li{
list-style: none;
margin-left: 10px;
margin-right: 10px;
padding-top: 1px;
padding-bottom: 1px;
padding-left: 3px;
padding-right: 4px;
}
/* #navbar ul li a{
} */
console.clear();
console.log("document.getElementById(`id1`)");
console.log(document.getElementById("id1"));
console.log("document.getElementsByClassName('hr-bar')");
console.log(document.getElementsByClassName("hr-bar"));
console.log("document.getElementsByTagName('div')");
console.log(document.getElementsByTagName("div"));
Browser Console
JS Query Selector-string
TOC
Query Selector-string allows to use CSS selector-strings to select HTML Elements.
1.
document.querySelector-string('css-selector-string-string');
A DOM method, arg: css-selector-string-string , returns: all HTML element matching the query.
2.
document.querySelector-stringAll('css-selector-string-string');
A DOM method, arg: css-selector-string-string , returns: all HTML element matching the query.
HTML CSS look of WebPage
gebcn , gebcn , gebtn are twice as fast as querySelector-strings
console.clear();
console.log("document.querySelector-stringAll('#navbar ul li')");
console.log(document.querySelector-stringAll("#navbar ul li"));
console.log("document.querySelector-string('#navbar ul li')");
console.log(document.querySelector-string("#navbar ul li"));
console.log('document.querySelector-stringAll("li1")');
console.log(document.querySelector-stringAll("#li1"));
</head>
<body>
<header>
<div>
<img id = 'bg-img' src="./Saturn.jpg" alt="Saturn Background"/>
<h1 id="countdown">
10
</h1>
</div>
</header>
<script src="./JS-notes.js"> </script>
</body>
</html>
*{
margin: 0;
padding: 0;
}
#countdown{
color: fuchsia;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 100px;
}
#bg-img{
width: 100%;
height: 100vh;
}
console.clear();
setInterval(function () {
initialCountdownVal = initialCountdownVal > 0 ? initialCountdownVal - 1 : 0;
countdownElement.innerHTML = initialCountdownVal;
selectedElement.style.{propertyName} = value;
Example:
selectedElement.style.width = '300px';
All the property names get converted to camel Case like font-size will get converted to fontSize .
HTML and CSS
The only difference in css of #example-2 and that of here is that the default fontSize of #countdown is
1000px here.
console.clear();
if(initialCountdownVal <= 0)
{
clearInterval(interval);
}
}, 1000);
Have a look at what o/p appears with above JS
Now we have an issue that the setInterval() continues to run without end. To stop it we can use
setInterval() as:
Note that all the changes in the styles that we have done by JS has been implemented in the inline CSS and
not in the actual CSS file.
A limitation to this method is that only those styles can be updated which can be written as inline styles.
i.e., we can update styles for pseudo classes and pseudo elements. There is no direct way to do this by JS.
JS Intro to Events
TOC
When some action happens in the webpage, that action is called event.
For example:
The user clicking the mouse over a certain element. *The user > hovering the cursor over a certain
element.
The user pressing a key on the keyboard.
The user resizing or closing the browser window.
A web page finishing loading.
A form being submitted.
A video being played, or paused, or finishing play.
Reacting to the events is called listening to events.
The code that that run on reaction to the events are called event handlers
Two ways for reacting to a event:
var selectedElement = getElementById('selector');
//or
var selectedElement = querySelector('selector');
//example
selectedElement.addEventListener('click', function() {});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Event Handler</title>
<style>
body{
margin: 0px;
font-family: sans-serif;
background-color: crimson;
}
header div {
width: 100%;
height: 100%;
box-sizing: border-box;
overflow: hidden;
position: relative;
}
#btn-click {
background-color: aliceblue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 100px;
}
</style>
</head>
<body>
<header><div> </div></header>
<button id="btn-click">
click
</button>
<script src="./JS-notes.js"> </script>
</body>
</html>
Using Method 1
var btn = document.getElementById('btn-click');
btn.onclick = ()=>{
alert("Button clicked");
}
OR the above code can also be written by passing a reference to the function:
var btn = document.getElementById('btn-click');
function onBtnClick() {
alert("Button clicked");
}
btn.onclick = onBtnClick();
When we write () while passing a reference to the function then the function is called
automatically, because if we use () then we aren't passing reference to the function instead
we are actually calling the function.
So, we need to do this to pass reference to the function
var btn = document.getElementById('btn-click');
function onBtnClick() {
alert("Button clicked");
}
btn.onclick = onBtnClick;
and we can also click the button by using the click() like:
Method 2:
var btn = document.getElementById('btn-click');
function onBtnClick() {
alert("Button clicked");
}
OR
var btn = document.getElementById('btn-click');
btn.addEventListener('click', ()=>{
alert("Button clicked");
});
Changing CSS using JS: changing background color on Button CLick
Math.random() returns a number in range [0, 1)
in the above code then it won't treat red, blue and green as variables as they are a part of a string.
Note that I have used function Hoisting here.
Add & Remove Classes from HTML using JS
TOC
classList holds all the classes of an HTML element.
var selectedElement = getElementById('selector')
// or
var selectedElement = querySelector('selector');
// Example
selectedElement.classList.add('show');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Event Handler</title>
<link rel="stylesheet" href="./JS-notes.css" type="text/css">
</head>
<body>
<header>
<div>
<h1 id="main-heading" class="small random-class">Add/Remove
Classes</h1>
<button id="btn-click">click</button>
</div>
</header>
<script src="./JS-notes.js"></script>
</body>
</html>
body {
margin: 0px;
font-family: sans-serif;
}
header > div {
width: 100%;
height: 100vh;
box-sizing: border-box;
overflow: hidden;
position: relative;
background-color: crimson;
text-align: center;
}
#btn-click {
font-size: 24;
}
#main-heading{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.small{
font-size: 24px;
}
.big{
font-size: 48px;
}
JS 1
var mainHeading = document.getElementById('main-heading');
console.log(mainHeading.classList);
mainHeading.classList.add('big');
console.log(mainHeading.classList);
setTimeout(() => {
mainHeading.classList.remove('big');
}, 3500);
console.log(mainHeading.classList);
classList will return a list DOMTokenList of classes of the element on which property is applied.
On adding big the classes in main-heading element will be "small random-class big"
since big is written after small in CSS so big will overwrite small.
JS 2 for doing above operation on clicking button
var mainHeading = document.getElementById('main-heading');
console.log(mainHeading.classList);
setTimeout(() => {
mainHeading.classList.remove('big');
console.log(mainHeading.classList);
}, 3500);
};
we can use contains property of classList to check whether a class is present or not like the above code
without using setTimeout() :
if (mainHeading.classList.conatins('big')) {
mainHeading.classList.add('small');
mainHeading.classList.remove('big');
} else {
mainHeading.classList.add('big');
mainHeading.classList.remove('small');
}
Inline Style
// Syntax
selectedElement.style.{inline-style-property};
// Example
selectedElement.style.width
CSS File
// Syntax
window.getComputedStyle(selectedElement).{Style-property-name}
// Example
window.getComputedStyle(selectedElement).width
<head>
<meta charset="UTF-8">
<title>JS Event Handler</title>
<link rel="stylesheet" href="./JS-notes2.css" type="text/css">
</head>
<body>
<header>
<div>
<button id="btn-decr">Font-</button>
<button id="btn-incr" style="margin-right: 0px; font-size: 36px;">Font+
</button>
<button id="IncDec">Inc-Dec</button>
</html>
body {
margin: 0px;
font-family: sans-serif;
}
header div {
width: 100%;
height: 100vh;
box-sizing: border-box;
overflow: hidden;
position: relative;
background-color: crimson;
text-align: center;
}
button {
font-size: 36px;
margin-top: 24px;
margin-right: 5px;
padding: 12px 24px;
}
#main-heading{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.small{
font-size: 24px;
}
.big{
font-size: 48px;
}
var IncDec = document.getElementById('IncDec');
var btnDec = document.getElementById('btn-decr');
var btnInc = document.getElementById('btn-incr');
var mainHeading = document.getElementById('main-heading');
console.log(1, IncDec.style);
// this element contains CSS file so it shows no values of css elements
console.log(2, btnInc.style.marginRight);
// this element contains inline style so it shows calculated value of styles
console.log(3);
console.log(3, window.getComputedStyle(IncDec).marginRight);
IncDec.onclick = ()=>{
var font = window.getComputedStyle(IncDec).fontSize;
// font will contain string : "24px"
console.log(4, font);
btnInc.onclick = ()=>{
console.log(5, window.getComputedStyle(mainHeading).fontSize);
console.log(6, mainHeading.style.fontSize);
}
btnDec.onclick = ()=>{
var mainHeadingFontSize = window.getComputedStyle(mainHeading).fontSize;
mainHeadingFontSize = Number(mainHeadingFontSize.substr(0,
(mainHeadingFontSize.length - 2)));
mainHeading.style.fontSize = mainHeadingFontSize - 2 + "px";
}
Form Events
TOC
change : Triggered when the content of an input field is changed or when the user selects a value from
the dropdown, etc;
focus : Triggered when the Input field is focused.
blur : Triggered when the Input field looses focus.
submit : Triggered when the submit button is clicked by user.
Content of a form field is accessed by value property.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Event Handler</title>
<link rel="stylesheet" href="./JS-notes2.css" type="text/css">
</head>
<body>
<form id="form">
<input type="text" id="username" name="username" placeholder="Username">
<br>
<input type="text" id="password" name="password" placeholder="Password">
<br>
<button id="submit">Submit</button>
</form>
<script src="./JS-notes2.js"></script>
</body>
</html>
body {
margin: 0px;
font-family: sans-serif;
}
button {
font-size: 20px;
margin-top: 4px;
padding: 4px;
}
form{
background-color: burlywood;
display: flex;
flex-direction:column;
justify-self: center;
align-items: center;
margin: 10px;
padding: 10px;
}
input{
font-size: medium;
margin: 5px;
border: 3px solid green;
border-radius: 10px;
padding: 10px;
outline: none;
}
#submit{
font-size: medium;
margin: 6px;
border: 2px solid crimson;
border-radius: 10px;
padding: 6px;
}
input Event :
will listen to every single change and will get updated even to the sligest of chage when the i/p field is in focus
username.addEventListener('input', ()=>{
console.log('changed: ', username.value);
});
// using `event` object
// we can use event object to know which element triggered the Event
username.addEventListener('input', (event)=>{
console.log(event.target, event.target.value);
var currVal = event.target.value;
currVal = currVal.toUpperCase();
console.log(currVal);
username.value = currVal;
});
username.addEventListener('focus', ()=>{
console.log('element focused');
});
username.addEventListener('blur', ()=>{
console.log('element lost focus');
});
It will generate a url with (name, value) pair and load that url
On using it the alert is shown, page don't get refreshed and the values are retained in the i/p fields.
var form = document.getElementById('form');
form.addEventListener('submit', (e)=>{
alert('form Submitted');
e.preventDefault();
// e is event object
});
Events Reference | MDN
Keyboard Events
TOC
Triggered when the user click a Key from Keyboard
3 Keyboard events:
keydown: Triggered when any key is pressed on the keyboard.
keyup : Triggered when any Key is released.
keypress : Triggered when any key other than shift, function, Capslock is in pressed position
Key Codes
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Event Handler</title>
<style>
body {
margin: 200px;
font-size: xx-large;
background-color: coral;
}
</style>
</head>
<body>
Something was here.
<script type="text/javascript" src="./JS-notes2.js"></script>
</body>
</html>
document.body.addEventListener('keydown', (e)=>{
var keyCode = e.keyCode;
// event object provides the number of the key clicked
console.log('a key was pressed');
});
document.body.addEventListener('keydown', (e)=>{
var keyCode = e.keyCode;
if(keyCode === 16)
console.log('key down, keyCode: ', keyCode);
});
document.body.addEventListener('keyup', (e)=>{
var keyCode = e.keyCode;
if(keyCode === 16)
console.log('key up, keyCode: ', keyCode);
});
document.body.addEventListener('keypress', (e)=>{
var keyCode = e.keyCode;
if(keyCode === 16)
console.log('key pressed, keyCode: ', keyCode);
});
Mouse Events
TOC
Triggered when different mouse keys are pressed/released or mouse pointer is moved over some part.
The availaible events are:
1. mousedown : when either left or right or middle mouse key is pressed on the HTML element.
2. mouseup : when either left or right or middle mouse key is released after the mousedown event.
3. click : when LEFT Mouse button is pressed and released on the same HTML element, it requires
mousedown and mouseup event to happen before click event.
4. dblclick : left mouse button is clicked twice on the same element.
See Img for events from 1 to 4.
5. mouseover : when mouse enters the HTML element and it's child elements.
6. mouseenter : when mouse enters the HTML element.
7. mousemove : triggered every time the mouse pointer is moved over the HTML element.
Events Reference | MDN
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Event Handler</title>
<link rel="stylesheet" href="./JS-notes2.css" type="text/css">
</head>
<body>
<button id="btn">CLick Me!!!</button>
<div id="maindiv">
<div id="mouseover" class="innerdiv">
<h3>Mouseover event triggered:</h3>
<p>0</p>
</div>
<div id="mouseenter" class="innerdiv">
<h3>Mouseenter event triggered:</h3>
<p>0</p>
</div>
<div id="mousemove" class="innerdiv">
<h3>Mousemove event triggered:</h3>
<p>0</p>
</div>
</div>
<script type="text/javascript" src="./JS-notes2.js"></script>
</body>
</html>
body {
margin: 0px;
background-color: burlywood;
}
button {
font-size: 20px;
margin-top: 4px;
padding: 4px;
position:relative ;
left: 45%;
}
.innerdiv{
font-size: medium;
margin: 2vh;
padding: 1vh;
width: 20%;
border: 3px solid chocolate;
display: inline-flex;
flex-direction: column;
}
h3{
padding: 5px;
border: 2px solid crimson;
border-radius: 5px;
}
p{
padding: 5px;
border: 3px solid salmon;
border-radius: 5px;
}
Events 1 to 4:
var btn = document.getElementById('btn');
console.log(btn);
btn.addEventListener('mousedown', ()=>{
console.log('mouse down event');
});
btn.addEventListener('mouseup', ()=>{
console.log('mouse up event');
});
btn.addEventListener('click', ()=>{
console.log('click event');
});
btn.addEventListener('dblclick', ()=>{
console.log('double click event');
});
Events 5: Mouseover
var mouseover = document.getElementById('mouseover');
var mouseoverCount = 0;
mouseover.addEventListener('mouseover', ()=>{
var count = document.querySelector('#mouseover > p');
// > will provide the immediate child of the element
mouseoverCount += 1;
count.innerHTML = mouseoverCount;
console.log('mouse over event');
});
Event 6 : Mouseenter
var mouseenter = document.getElementById('mouseenter');
var mouseenterCount = 0;
mouseenter.addEventListener('mouseenter', ()=>{
var count = document.querySelector('#mouseenter > p');
// > will provide the immediate child of the element
mouseenterCount += 1;
count.innerHTML = mouseenterCount;
console.log('mouse enter event');
});
Event 7 : Mousemove
var mousemove = document.getElementById('mousemove');
var mousemoveCount = 0;
mousemove.addEventListener('mousemove', ()=>{
var count = document.querySelector('#mousemove > p');
// > will provide the immediate child of the element
mousemoveCount += 1;
count.innerHTML = mousemoveCount;
console.log('mouse over event');
});
<head>
<meta charset="UTF-8">
<title>JS Event Handler</title>
<link rel="stylesheet" href="./JS-notes2.css" type="text/css">
</head>
<body>
<header>
<section>
<button id="add-item">Add List Item</button>
<ul id="todo-list">
<li id="li1">List Item 1</li>
<li id="li2">List Item 2</li>
</ul>
</section>
</header>
<script type="text/javascript" src="./JS-notes2.js"></script>
</body>
</html>
body {
margin: 0px;
background-color: burlywood;
}
button {
font-size: 20px;
margin-top: 4px;
padding: 4px;
position:relative ;
left: 45%;
}
ul{
font-size: medium;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
li{
margin: 2vh;
padding: 1vh;
border: 3px solid chocolate;
width: 60%;
display: flex;
justify-content: center;
JS 1
// creating a list node
var newListElt = document.createElement('li');// arg passed is tagname
listCount = list.childElementCount;
var newListElt = document.createElement('li');
var textNode = document.createTextNode('List Item ' + (listCount + 1));
newListElt.appendChild(textNode);
newListElt.id = 'li' + (listCount + 1);
console.log(newListElt);
btnAdd.addEventListener('click', () => {
listCount = list.childElementCount;
// creating a list node
var newListElt = document.createElement('li');
//creating a text node
var textNode = document.createTextNode('List Item ' + (listCount + 1));
newListElt.id = 'li' +(listCount + 1)
newListElt.appendChild(textNode);
console.log(newListElt);
list.insertBefore(newListElt, firstElt);
});
<head>
<meta charset="UTF-8">
<title>JS Event Handler</title>
<link rel="stylesheet" href="./JS-notes2.css" type="text/css">
</head>
<body>
<header>
<section>
<div id="start">
<!-- If <input> is placed under <form> then on pressing enter key
inside the input box
it will generate a link and open it else it's working fine -->
<input type="text" placeholder="Enter Todo Item" id="input"
name="input">
<span>
<button id="add-item">Add List Item</button>
<button id="update-item">Update First Item</button>
<button id="remove-item">Remove First Item</button>
</span>
</div>
<ul id="todo-list">
<li id="li1">List Item 1</li>
<li id="li2">List Item 2</li>
</ul>
</section>
</header>
<script type="text/javascript" src="./JS-notes2.js"></script>
</body>
</html>
body {
margin: 0px;
background-color: burlywood;
}
#start {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
button, input {
font-size: medium;
margin: 4px;
padding: 8px;
border: 3px solid brown;
border-radius: 7px;
background-color: violet;
}
ul{
font-size: medium;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
li{
margin: 2vh;
padding: 1vh;
border: 3px solid chocolate;
border-radius: 7px;
width: 60%;
display: flex;
justify-content: center;
}
var btnAdd = document.getElementById('add-item');
var input = document.getElementById('input');
var list = document.getElementById('todo-list');
function addItem() {
var text = input.value;
if (input.value) {
list.appendChild(listNode);
input.value = '';
}
else
alert(`Empty TODO item`);
}
btnAdd.addEventListener('click', addItem);
input.addEventListener('keyup', (e) => {
if (e.keyCode === 13) {
addItem();
}
});
<head>
<meta charset="UTF-8">
<title>JS Event Handler</title>
<link rel="stylesheet" href="./JS-notes2.css" type="text/css">
</head>
<body>
<header>
<section>
<div id="start">
<form id="form">
<input type="text" placeholder="Enter Todo Item" id="input"
name="input">
</form>
<span>
<button id="add-item">Add List Item</button>
<button id="update-item">Update First Item</button>
<button id="remove-item">Remove First Item</button>
</span>
</div>
<ul id="todo-list">
<li id="li1">List Item 1</li>
<li id="li2">List Item 2</li>
</ul>
</section>
</header>
<script type="text/javascript" src="./JS-notes2.js"></script>
</body>
</html>
body {
margin: 0px;
background-color: burlywood;
}
#start {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
button, input {
font-size: medium;
margin: 4px;
padding: 8px;
border: 3px solid brown;
border-radius: 7px;
background-color: violet;
}
ul{
font-size: medium;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
li{
margin: 2vh;
padding: 1vh;
border: 3px solid chocolate;
border-radius: 7px;
width: 60%;
display: flex;
justify-content: center;
}
var btnAdd = document.getElementById('add-item');
var input = document.getElementById('input');
var list = document.getElementById('todo-list');
function createListNode(){
var text = input.value;
var textNode = document.createTextNode(text);
var listNode = document.createElement('li'); // arg is tagName
var listCount = list.childElementCount;
listNode.id = 'li' + (listCount + 1);
console.log(3, listNode);
listNode.appendChild(textNode);
// yaha tk hmne listNode ko bana lia hai.
return listNode
}
function addItem() {
if (input.value) {
var listNode = createListNode();
list.appendChild(listNode);
input.value = '';
}
else
alert(`Empty TODO item`);
}
btnAdd.addEventListener('click', addItem);
input.addEventListener('keyup', (e) => {
/**ADD LIST ITEM */
if (e.keyCode === 13) {
addItem();
}
});
btnUpdate.addEventListener('click', () => {
/**UPDATE FIRST ELEMENT */
var firstElement = list.firstElementChild; // provides the first child element
of the list
var listNode = createListNode();
btnRemove.addEventListener('click', ()=>{
/**REMOVE FIRST ITEM */
var firstElement = list.firstElementChild;
list.removeChild(firstElement);
});
<head>
<meta charset="UTF-8">
<title>JS Event Handler</title>
<link rel="stylesheet" href="./JS-notes2.css" type="text/css">
</head>
<body>
<header>
<section>
<div id="start">
<!-- If input is placed under form tag then on pressing enter key
inside the input box
it will generate a link and open it else it's working fine -->
<input type="text" placeholder="Enter Todo Item" id="input"
name="input">
<span>
<button id="add-item">Add List Item</button>
<button id="update-item">Update First Item</button>
<button id="remove-item">Remove First Item</button>
</span>
</div>
<ul id="todo-list">
<li id="li1">List Item 1 <button class="delmoji" id="bin1"> 🗑
</button></li>
<li id="li2">List Item 2 <button class="delmoji" id="bin2"> 🗑
</button></li>
</html>
body {
margin: 0px;
background-color: rgb(53, 50, 46);
}
#start {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
input, span > button {
font-size: medium;
border: 3px solid brown;
background-color: violet;
margin: 1vh;
padding: 1vh;
border-radius: 7px;
/* width: 20%; */
}
ul{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
li{
font-size: medium;
margin: 1vh;
padding: 4px;
border: 3px solid chocolate;
background-color: rgb(127, 111, 74);
border-radius: 7px;
width: 60%;
display: flex;
}
.delmoji{
margin-right: 7px;
margin-left: auto;
font: xx-large bold;
}
var btnAdd = document.getElementById('add-item');
var input = document.getElementById('input');
var list = document.getElementById('todo-list');
function createListNode() {
listNode.appendChild(delMojiBtn);
return listNode
}
function addItem() {
if (input.value) {
var listNode = createListNode();
list.appendChild(listNode);
input.value = '';
}
else
alert(`Empty TODO item`);
}
btnAdd.addEventListener('click', addItem);
input.addEventListener('keyup', (e) => {
/**ADD LIST ITEM */
if (e.keyCode === 13) {
addItem();
}
});
btnUpdate.addEventListener('click', () => {
/**UPDATE FIRST ELEMENT */
var firstElement = list.firstElementChild; // provides the first child element
of the list
var listNode = createListNode();
btnRemove.addEventListener('click', () => {
/**REMOVE FIRST ITEM */
var firstElement = list.firstElementChild;
list.removeChild(firstElement);
});
// to delete by using delete emoji we will have to add event listener to all the
emojis
function bin(delmojiId) {
// alert('you are about to delete');
var delmoji = document.getElementById(delmojiId);
document.addEventListener('click', (e)=>{
if (e.target.className == "delmoji") {
bin(e.target.id);
console.log(e.target.id); // will display the id of the delmoji clicked as
string
}
});
Part 3
Window is a object
Document object represent the webpage structure in a tree format
History object holds the data about the orders that have been listed by the user.
Screen object holds the information about the browser screen, like width or height.
Navigator object contains information about the user's borwser.
The Window Object
window.document.getElementById('')
// or simply
document.getElementById('')
window.alert('')
// or simply
alert('')
We can access them without the window object because all the Global JS objects and functions and variables
automatically become members of the window object.
innerwidth/innerheight represents the width/height of the part of the browser window which shows the webpage
content
Methods under the Window Object
setTimeout()
setInterval
alert()
confirm()
prompt() example
→
it's a string
Screen and Navigator Object
TOC
availWidth will remain same as width unless something else occupies the widht of pc screen because that
much width will remain availaible for the webpage.
similar is availHeight .
The Navigator Object
Contains information about the browser where your application is running.
User Agent String can be parsed using some parser like: User Agent String Parser
To check if the user has an active interner or not. navigator.onLine is showing true even when offline
History and Location Object
TOC
It represents an array of URLs visited by the user.
It provides two methods:
back() : It loads the previous page from the browser History.
Location Object
Can be used to get details of the current page address.
It can also redirect the browser to a new page in the same browser tab.
window.location;
window.location.href; // provides the url pesent in the tab.
window.location.hostname;
ex:
JS Regular Expressions
Introduction to Regular Expressions
TOC
Regular Expression is an Object that describes a pattern of text using the defined patterns.
ex:
To check whether a given string is a valid email or not.
To check that an entered username should only contain alphabets and numbers.
It can also be used to find on or replace parts of strings based on certain patterns.
Syntax :
/pattern-string/flags
2. Second variation may contain Square brackets may also contain charachet ranges.
[A-Z] is a character in range from A to Z , and [0-9] is a digit from 0 to 9 .
Example:
String: Same Name Fame Glam.
Pattern: [A-Z]ame
only decimal ranges are accepted like [0-5] is from 0 to 5 but [45-55] is not valid because the set and
ranges are selected one element at a time.
. is a Meta-character which selects all the 256 chars.
Complex Expressions
1.
2.
3.
4.
/s is used for detecting space
\d is called character class for [0-9]
to select all chars oher than numbers: [^0-9] character class for it is: \D
to select all alphabets, digits and underscore _ : [a-zA-Z0-9_] character class for it is: [\w]
Regex Quantifiers
TOC
Quantifiers select a value multiple times. They decide how many times a value should be selected.
Syntax:
To define a quantifier, we add a value inside curly braces after the sets or ranges.
For Example:
/[\d]{3}/g will select number with 3 digits
$ checks whether a string ends with a certain String, $ checks if the last pattern in regex is present in the
string or not.
regex: /^#[\w]{6}/g means that look for a string which starts with # and has exact 6 characters which can be
numbers or alphabets or underscore(since \w also contains _ ).
/https?/g ≈ /https{0,}/g
? means that whatever it follows can either have occurence 0 or 1 time(s)
Using Regex in JS
TOC
2 ways to define Regex in JS
1. Syntax: /{pattern}/{flags}
2. inbuilt Regex class:
Syntax: new RegExp("pattern", "flags")
flags are optional
Regex Methods in JS :
str.search(pattern) - It returns the string position of the first match. -1 is returned if no match is
foung
pattern.test(str) - Returns true if there is a match and returns false if no match.
str.match(pattern) - Returns the matched string. If the flag is not set to global then it returns only the
first match. But if the flag is set to global then returns an array of matches.
1st Way
var str = "This is a black ball pen. This pen is really smooth. It is a parker
PEN.";
console.log(1, str.search(pattern1));
console.log(2, str.search(pattern2));
console.log(7, str.search(pattern3));
console.log(3, pattern1.test(str));
console.log(4, pattern2.test(str));
console.log(8, pattern3.test(str));
console.log(5, str.match(pattern1));
console.log(6, str.match(pattern2));
console.log(9, str.match(pattern3));
Output:
2nd Way
var str = "This is a black ball pen. This pen is really smooth. It is a parker
PEN.";
console.log(1, str.search(pattern));
console.log(3, pattern.test(str));
console.log(5, str.match(pattern));
Output
console.log(1, str.search(pattern));
console.log(3, pattern.test(str));
console.log(5, str.match(pattern));
Regex Groups
TOC
The Problem:
we want to select a Indian mobile number with or without starting with 91
1.
var str = "9876543211";
var pattern = /[\d]{10}$/g;
console.log(str.match(pattern));
/* Output:
[ '9876543211' ]
*/
2.
var str = "919876543211";
var pattern = /^[\d]{10}$/g;
console.log(str.match(pattern));
/* Output:
null
*/
3.
var str = "919876543211";
var pattern = /^9?1?[\d]{10}$/g;
console.log(str.match(pattern));
/* Output:
[ '919876543211' ]
*/
The Solution
Using Regex Groups
var pattern = /^(91)?[\d]{10}$/g;
//here (91) becomes optional
var str1 = "19876543211";
var str2 = "99876543211";
var str3 = "9876543211";
console.log(str1.match(pattern));
console.log(str2.match(pattern));
console.log(str3.match(pattern));
/* Output
null
null
[ '9876543211' ]
*/
+ has a special meaning to Regex it acts as a Quantifier so if we want the Regex to consider it as string a \+
is used.
var pattern = /^(\+)?(91)?[\d]{10}$/g;
var str1 = "+919876543211";
var str2 = "919876543211";
console.log(str1.match(pattern));
console.log(str2.match(pattern));
/* Output
[ '+919876543211' ]
[ '919876543211' ]
*/
/* Output
[ 'www.google.com' ]
*/
www\. is used so that . is treated as char or else 'www.', 'wwwa', etc. will also get selcted
[\w]+ deontes some sequence of char
<head>
<meta charset="UTF-8">
<title>JS Event Handler</title>
<link rel="stylesheet" href="./JS-notes2.css" type="text/css">
</head>
<body>
<div>
<h1>Never delete the css from the css file</h1>
</div>
<form id="login-form">
<div class="container">
<input type="text" id="username" placeholder="Enter Username"
name="username" required>
<p id="usernameError">Please enter a valid Username</p>
<input type="password" id="password" placeholder="Enter Password"
name="password" required>
<button type="submit">Login</button>
</div>
</form>
</html>
body {
margin: 0px;
background-color: rgb(53, 50, 46);
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
form{
color:tan;
font-family: Georgia, 'Times New Roman', Times, serif;
font: message-box;
}
input, button {
font-size: medium;
border: 3px solid brown;
background-color: violet;
margin: 1vh;
padding: 1vh;
border-radius: 7px;
}
#usernameError{
display: none;
}
var username = document.getElementById('username');
var loginForm = document.getElementById('login-form');
var usernameError = document.getElementById('usernameError');
username.addEventListener('input', (e)=>{
// e is the event object
if(username_value == '')
{
usernameError.style.display = 'none';
}
else if(regex.test(username_value))
{
usernameError.style.display = 'none';
}
else
{
usernameError.style.display = 'block';
}
});
OOP in JavaScript
Introduction to OOP in JS
TOC
1.
When we don't use OOP, we have a lot of dependencies in between different parts of the code like a function
dependent on different other functions. In that case if we make changes to one part of the code then we may end
up breaking the other parts of the code.
2.
To avoid above inconsistencies we use object oriented programming.
In OOP in JS we combine different variables and functions into one unit. This unit is called as object. This way of
combining into one unit is encapsulation.
3.
var videoName = "intro to JS";
var name = "Adarsh";
var duration = "2:48";
function getVidName() {
return videoName;
}
function getDuration() {
return duration;
}
function getNname() {
return name;
}
getVidName: ()=>{
return this.videoName;
} ,
getDuration: ()=>{
return this.duration;
} ,
getName: ()=>{
return this.name;
}
}
this keyword
TOC
this keyword refers to the current context.
It always refers to a single object.
It is usually inside a function or a method to access properties and methods which are a part of the object
which is associated with the function.
In JavaScript, the thing called this is the object that "owns" the code.
The value of this , when used in an object, is the object itself.
In a constructor function this does not have a value. It is a substitute for the new object. The value of
this will become the new object when a new object is created.
var firstName = "Adarsh";
var person = {
firstName : "Jack",
yearOFBirth: 1990,
job: "Pilot",
getName: function () {
console.log( 1, this.firstName );
console.log( 2, firstName );
} ,
parents: {
firstName : "Ryan",
yearOFBirth: -1234,
job: "Yodha",
getName: function () {
console.log( 3, this.firstName );
console.log( 4,firstName );
}
}
}
person.getName();
person.parents.getName();
Output
Constructor Functions
TOC
Generating multiple objects of the same functions.
In other Prog Lang → class is similar as Constructor/Prototype Function in JS.
Based on the Constructor/Prototype Function we can create any number of objects and these objects are
called Instances the instances created are of object type .
1.
2.
3.
4.
⚠️ ℹ️ Ⓜ️ 🅿️ 🅾️ 🇷🇹 🅰️ 🇳🇹
Constructor example from W3School JS Constructors
It is considered good practice to name constructor functions with an upper-case first letter.
function Person(firstName, lastName, age, mobNo )
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.mobNo = mobNo;
this.showName = ()=>{
console.log("Full Name is: ", this.firstName, this.lastName);
}
}
myPa.showName();
myMa.showName();
Hk.showName();
Hk.changeName = ()=>{
Hk.lastName = 'Kumar Singh';
console.log("Full Name is: ", Hk.firstName, Hk.lastName);
}
console.log(Hk);
Hk.changeName();
Output:
📓📝
The Math() object is not in the list. Math is a global object. The new keyword cannot be used on Math.
Read the link of W3School carefully that's it.
Primitive Values are much faster than their Objects
Inheritancs and Prototype Chain
TOC
Every JS Object has a property called prototype.
This prototype property makes it possible to inherit methods and properties to the child object.
1.
2.
3.
For John child object to be able to access the calculateAge() method of the Person Object then it should be
present in the prototype property of the Person Object.
Similarly any other object created by the Person Object will automatically inherit the calculateAge() property.
A Person prototype property is not the prototype of the person but for all he instances created from the person
object.
4.
5.
All the objects created are objects of the JavaScript Object
6.
7.
null is the final link in the prototpye chain.
If we write john.toString() then it will try to find the funcyion in the following manner:
First it will search inside the Prototype of John object (which is the prototpye of the Person )
second it will look in Prototype of Person Object (which is the prototype of the JS Object).
If still not found then it will look into the null where it will gt the value undefined .
Prototype Implementation
TOC
function Person(pName, pYearOfBirth, pJob)
{
this.name = pName;
this.YearOfBirth = pYearOfBirth;
this.job = pJob;
this.calculateAge = function () {
console.log("age: ", 2021-this.YearOfBirth);
}
}
Person.prototype.displayName = function()
/**By this statement we have added a function to the Person constructor function
*This function will be accessible to all the child of it
*/
{
console.log('name is: ', this.name);
}
2.
3.
Note that the function dispalyName() is displayed in the __proto__ and not in the object john .
Basically what happens is that when a new object of the some object is created then the exact same code (of
Constructor) is copied for it's Object.
Instead of copying the exact code we can pass some piece of code as reference to prevent unnecessary
copying of the code.
In the above example the displayName() function is passed as reference into object john , i.e., the code is
not copie into john but a reference is passed into john so that if displayName() function is called then it's
called from the constructor Person() and not from the object john .
It reduces the memory sixe of the code.
The above functions were for fetching the data. To set the data we can do:
Add the following code in the above code.
Person.prototype.changeName = function (newName) {
this.name = newName;
}
Adarsh.displayName();
Adarsh.changeName('AKS');
Adarsh.displayName();
output:
These methods for getting and setting values are called getters and setters respectively.
JS HTTP Requests
Understanding Frontend and Backend
TOC
1.
2.
3.
HTTP Requests and Responses
TOC
1.
Most used HTTP Methods for different requests:
2.
To send request to the Backend we will use some URL which will connect to the backend and tell Backend how to
handle the request.
3.
consider /todo similar to /contact.html or /index.html
The backend server sends a response along with the status code to tells us about the success or failure of the
request.
4.
500 also means that the backend doesn't know how to handle the request.
Introduction to JSON
TOC
1.
JSON are different from JS Objects
JS Obhects:
var mObj = {
name: "john",
age: 20
}
JSON object:
var mObj = {
"name": "john",
"age": 20
}
2.
JSON Array:
var arr = [
{
"name": "John",
"age": 20
},
{
"name": "Smith",
"age": 30
},
{
"name": "Maxwell",
"age": 40
},
]
console.log(1, arr[0]);
console.log(2, arr[1].name);
3.
JSON objects can be converted to String and those String can be converted back to the JSON object.
var mObj = {
"name": "Smith",
"age": 30
}
console.log(1, mObj.toString());
4.
Output in Node.JS REPL:
5.
Unlike JS Objects JSON cann't hold functions and Undefined . It will simply ignore the keys:
var mObj = {
"name": "Smith",
"age": 30,
"someKey": undefined,
"FunnKey": function () {
console.log('hello');
},
"marks": { 'maths': 30, },
'key1': null,
'key2': undefined,
console.log(1, mObj.toString());
console.log(1, mObj);
Introduction to AJAX
TOC
📓📝
AJAX : Asynchronous JavaScript and XML.
It allows web pages to be updates asynchronously by exchanging data with the backend.
This makes it possible to update parts of a web page, without reloading the whole page.
Initially AJAX was used to send and receive XML because that was how the data was received from the
backend in old days.
But now it can also be used to send/receive JSON objects, which is pretty common these days.
1.
ex: Sending of request to backend and fetching response from it may take even more than 5 seconds.
So we can make backend requests as Asynchronous to avoid freezing of the webpage for that long.
If it would have been synchronous then it would not process the later tasks and will wait for that time.
2.
Let we want get some TODO Items from the backend in our TODO app
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Event Handler</title>
<link rel="stylesheet" href="./JS-notes2.css" type="text/css">
</head>
<body>
<header>
<section>
<div id="start">
<!-- If input is placed under form tag then on pressing enter key
inside the input box
it will generate a link and open it else it's working fine -->
<input type="text" placeholder="Enter Todo Item" id="input"
name="input">
<span>
<button id="add-item">Add List Item</button>
<button id="update-item">Update First Item</button>
<button id="remove-item">Remove First Item</button>
</span>
</div>
<ul id="todo-list">
<li id="li1">List Item 1 <button class="delmoji" id="bin1"> 🗑
</button></li>
<li id="li2">List Item 2 <button class="delmoji" id="bin2"> 🗑
</button></li>
</html>
body {
margin: 0px;
background-color: rgb(53, 50, 46);
}
#start {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
input, span > button {
font-size: medium;
border: 3px solid brown;
background-color: violet;
margin: 1vh;
padding: 1vh;
border-radius: 7px;
/* width: 20%; */
}
ul{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
li{
font-size: medium;
margin: 1vh;
padding: 4px;
border: 3px solid chocolate;
background-color: rgb(127, 111, 74);
border-radius: 7px;
width: 60%;
display: flex;
}
.delmoji{
margin-right: 7px;
margin-left: auto;
font: xx-large bold;
}
var btnAdd = document.getElementById('add-item');
var input = document.getElementById('input');
var list = document.getElementById('todo-list');
function createListNode() {
listNode.appendChild(delMojiBtn);
return listNode
}
function addItem() {
if (input.value) {
var listNode = createListNode();
list.appendChild(listNode);
input.value = '';
}
else
alert(`Empty TODO item`);
}
btnAdd.addEventListener('click', addItem);
input.addEventListener('keyup', (e) => {
/**ADD LIST ITEM */
if (e.keyCode === 13) {
addItem();
}
});
btnUpdate.addEventListener('click', () => {
/**UPDATE FIRST ELEMENT */
var firstElement = list.firstElementChild; // provides the first child element
of the list
var listNode = createListNode();
btnRemove.addEventListener('click', () => {
/**REMOVE FIRST ITEM */
var firstElement = list.firstElementChild;
list.removeChild(firstElement);
});
// to delete by using delete emoji we will have to add event listener to all the
emojis
function bin(delmojiId) {
// alert('you are about to delete');
var delmoji = document.getElementById(delmojiId);
document.addEventListener('click', (e)=>{
if (e.target.className == "delmoji") {
bin(e.target.id);
console.log(e.target.id); // will display the id of the delmoji clicked as
string
}
});
getTodoListFromBackend();
3.
4.
5.
So we can see that our call was executed and we got the response.
In order to access the response we need to handle it.
Handling HTTP Response
1.
readyState property holds the status of the request that is sent.
2.
function getTodoListFromBackend() {
var http = new XMLHttpRequest();
http.onreadystatechange = function () {
if (this.readyState === 0) {
console.log(this.readyState, 'UNSENT- Request initiated but open()
function not called, i.e., we have created the instance of the object but open()
fnc. isn\'t called yet');
}
else if (this.readyState === 1) {
console.log(this.readyState, 'OPENED- open() function called');
}
else if (this.readyState === 2) {
console.log(this.readyState, 'HEADERS RECEIVED- sent() func. called');
}
else if (this.readyState === 3) {
console.log(this.readyState, 'LOADING- request processing');
}
else if (this.readyState === 4) {
console.log(this.readyState, 'DONE- Request complete and response is
ready, but it doesn\'t tells whether the response is success or failure');
// to access the actual response as a string
// console.log(this.responseText);
}
http.open('GET', 'http://jsonplaceholder.typicode.com/todos', true);
http.send();
}
The function defined by the property onreadystatechange will be run every time the value of property
readyState changes. It's Asynchronous
Output:
Inside the last else if part we can do this to print the title and id of all the JSON Objects:
else if (this.readyState === 4) {
console.log(this.readyState, 'DONE- Request complete and response is ready, but
it doesn\'t tells whether the response is success or failure');
if (this.status === 200) {
console.log(JSON.parse(this.responseText));
var response = JSON.parse(this.responseText);
for (var i = 0; i < response.length; i++) {
console.log(`${i}, title: ${response[i].title} , id:
${response[i].id}`);
}
}
else {
console.log('call failed');
}
}
To add all the elements from the JSON array on a button click. Add the functions written below.
var TodoBackend = document.getElementById('todo-backend');
TodoBackend.addEventListener('click', () => {
console.log('todo-backend');
getTodoListFromBackend();
});
newListElement.appendChild(delMojiBtn);
return newListElement;
}
http.send(obj);
}
1.
2.
3.
Request Payload shows the data that was send.
4.
Hence our call was successful and the data was successfully sent to the backend and we can handle the response
by adding the newly sent item in the todo-list.
Output looks like:
5.
http.send(obj);
http.onreadystatechange = function () {
console.log('createTodoItemAtBackend');
if (this.readyState === 4) {
console.log('DONE- Request is complete and response is ready');
else {
console.log('readyState != 4');
}
}
}
⚠️ Ⓜ️ 🅿️ 🅾️ 🇷🇹 🅰️ 🇳🇹 📓📝
There might have been some minor changes in the final JS and HTML of the TODO List project
So the Final HTML and JS Looks Like.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Event Handler</title>
<link rel="stylesheet" href="./JS-notes2.css" type="text/css">
</head>
<body>
<header>
<section>
<div id="start">
<!-- If 'input tag' is placed under form tag then on pressing enter
key inside the input box
it will generate a link and open it. If Form tag not used then
it's working fine -->
<input type="text" placeholder="Enter Todo Item" id="input"
name="input">
<span>
<button id="add-item">Add List Item</button>
<button id="update-item">Update First Item</button>
<button id="remove-item">Remove First Item</button>
<button id="todo-backend">Add Items from Backend</button>
</span>
</div>
<ul id="todo-list">
<li id="li1">List Item 1 <button class="delmoji" id="bin1"> 🗑
</button></li>
<li id="li2">List Item 2 <button class="delmoji" id="bin2"> 🗑
</button></li>
</ul>
</section>
</header>
<script type="text/javascript" src="./JS-notes2.js"></script>
</body>
</html>
var btnAdd = document.getElementById('add-item');
var input = document.getElementById('input');
var list = document.getElementById('todo-list');
function createListNode() {
listNode.appendChild(delMojiBtn);
return listNode
}
function addItem() {
if (input.value) {
var listNode = createListNode();
list.appendChild(listNode);
input.value = '';
}
else
alert(`Empty TODO item`);
}
btnAdd.addEventListener('click', createTodoItemAtBackend);
btnUpdate.addEventListener('click', () => {
/**UPDATE FIRST ELEMENT */
var firstElement = list.firstElementChild; // provides the first child element
of the list
var listNode = createListNode();
btnRemove.addEventListener('click', () => {
/**REMOVE FIRST ITEM */
var firstElement = list.firstElementChild;
list.removeChild(firstElement);
});
// to delete by using delete emoji we will have to add event listener to all the
emojis
function bin(delmojiId) {
// alert('you are about to delete');
var delmoji = document.getElementById(delmojiId);
function getTodoListFromBackend() {
var http = new XMLHttpRequest();
console.log(createTodoDynamically(response[i].id,
response[i].title));
createTodoDynamically(response[i].id, response[i].title);
}
}
else {
console.log('Call Failed');
}
}
else {
console.log('readyState != 4');
}
}
}
// getTodoListFromBackend();
function createTodoItemAtBackend() {
alert('called');
// this function will be called from the 'click' eventListener of the btnAdd.
// btnAdd.addEventListener('click', createTodoItemAtBackend);
http.send(obj);
http.onreadystatechange = function () {
console.log('createTodoItemAtBackend');
if (this.readyState === 4) {
console.log('DONE- Request is complete and response is ready');
else {
console.log('readyState != 4');
}
}
}
jQuery
Introduction
TOC
It's very small in size.
1.
2.
jQuery needs less code than normal JS to perform the same functionality.
3.
uncompressed, minified, slim, slim minified are different flavours of the jQuery.
To use the minified flavour copy the script and paste it into the head tag:
4.
5.
After this step the setup for using jQuery is done.