Javascript Learning
Javascript Learning
Mouse Events
2. Keyboard Events
3. Form Events
5. Clipboard Events
8. Media Events
9. Miscellaneous Events
Event Listeners
javascript
Copy code
Fixed in the center of the image in the middle of the it by the css property
Combinators of the css :
DesCription List :
To create the html form :
Formatting types ;
To apply css in the html
------------------------------------------------------------------------------
------------------------------------------------------------------------------
---
"selector": "source.js",
"working_dir": "$file_path",
Link the js file to the html file. Js file will show on the screen with the html
code
Difference b/w null and undefined:
String slice method:
.slice((0_based,1_based))
console.log(result); // "hello-world"
console.log(result); // "hello_world_this_is_JS"
console.log(result); // "helloworld"
let result = str.split(",").reverse().join(" | "); // Reverse the order and join with a pipe
let result = arr.join(", "); // Joins array elements with a comma and a space
console.log(result); // "1-2-3-4-5"
.include() it checks the substr is present or not .. returns the True / False
Template Literals
Switch Case Basic
Arrow function - a concise way to write the simple function that you can
only use once (parameter) => some code
For this one statement we don’t need to use the return
IMP : A arrow function can ‘t be used with the this keyword (because it
assumes the windows object i.e {empty})
Important :
The person2 copies all the members of the person but with the change of
the only name i.e ‘jack’
Use of the Static and Class
This keyword refers to the current object. It can access the property of an
object
Laptop1.compare(Laptop2) this is how it’ll work
Use the constructor and the New keyword that represent the 5 different
object for the 5 new types of the object calling
If we try to return other than object from the constructor it just skip it. And
gives no error
DESTRUCTURING
A another way
If we want to skip the element
Even this is also cool but only for the single variable
The map method keeps the original array returns the new array but forEach
will change them
Pass value and the key
Use case of the Reduce function to a one value output which takes two
values to perform the operation
Use of the Set
Function Expressions
Use case of the Super keyword
super.useParentMethod(arg1,arg2)
Closure
Used the Get method to access the property of the Inner Function
SetTimeOut
// digital clock
function updateClock() {
const now = new Date();
let h = now.getHours();
const medium = h >= 12 ? "PM" : "AM";
h = h % 12 || 12;
h = h.toString().padStart(2, 0);
const m = now.getMinutes().toString().padStart(2, '0');
const s = now.getSeconds().toString().padStart(2, '0');
const timeStr = `${h}:${m}:${s}`;
document.getElementById("clock").textContent = timeStr;
}
updateClock();
// to get the clock update every second
setInterval(updateClock, 1000);
======================================================
===========================================
STOPTIME PROJECT 2
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body{
display: flex;
flex-direction: column;
align-items: center;
background-color: hsl(0, 0%, 90%);
}
#h1{
font-size:4rem;
font-family: "Arial", sans-serif;
color: hsl(0, 0%, 25%);
}
#container{
display: flex;
flex-direction: column;
align-items: center;
padding: 30px;
border: 5px solid;
border-radius: 50px;
background-color: white;
}
#display{
font-size: 5rem;
font-family: "Arial", sans-serif;
font-weight: bold;
color: hsl(0, 0%, 30%);
text-shadow: 2px 2px 2px hsl(0,0%,0%,0.75);
margin-bottom: 25px;
}
#control button{
font-size: 1.5rem;
font-weight: bold;
padding: 10px 20px;
margin: 5px;
min-width: 125px;
border: none;
border-radius: 10px;
cursor: pointer;
color: white;
text-shadow: 2px 2px 2px hsl(0,0%,0%,0.9);
transition: background-color 0.5s ease;
}
#startBtn{
background-color: hsl(115, 100%, 40%);
}
#startBtn:hover{
background-color: hsl(115, 100%, 25%);
}
#stopBtn{
background-color: hsl(10, 90%, 50%);
}
#stopBtn:hover{
background-color: hsl(10, 90%, 35%);
}
#resetBtn{
background-color: hsl(205, 90%, 60%);
}
#resetBtn:hover{
background-color: hsl(205, 90%, 45%);
}
</style>
</head>
<body>
<h1 id="h1">Stopwatch</h1>
<div id="container">
<div id="display"> 00:00:00:00</div>
<div id="control">
<button id="startBtn" onclick="start()">start</button>
<button id="stopBtn" onclick="stop()">stop</button>
<button id="resetBtn" onclick="reset()">reset</button>
</div>
</div>
<script src="temp.js"></script>
</body>
</html>
======================================================
===========================================
ES6 module :
Set the html file to type = “module”
Calculator Project :
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body{
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vm;
background-color: hsl(0, 0%, 95%);
}
#cal{
font-family: Arial, sans-serif;
background-color: hsl(0, 0%, 15%);
border-radius: 15x;
max-width: 500px;
overflow: hidden;
}
#display{
width: 100%;
padding: 20px;
font-size: 5rem;
text-align: left;
border: none;
background-color: hsl(0, 0%, 20%);
color: white;
}
#keys{
display:grid;
grid-template-columns:repeat(4, 1fr); /*take the even space */
gap: 10px;
padding: 25px;
}
button{
width: 100px;
height: 100px;
border-radius: 50px;
border: none;
background-color: hsl(0, 0%, 30%);
color: white;
font-size: 3rem;
font-weight: bold;
cursor: pointer;
}
button:hover{
background-color: hsl(0,0%,40%);
}
button:active{
background-color: hsl(0,0%,50%); /*click flashy*/
}
.op-btn{
background-color:hsl(35,100%,50%);
}
.op-btn:hover{
background-color:hsl(35,100%,65%);
}.op-btn:active{
background-color:hsl(35,100%,75%);
}
</style>
</head>
<body>
<div id ="cal">
<input id="display" type="text" readonly>
<div id="keys">
<button onclick="calFunc('+')" class="op-btn">+</button>
<button onclick="calFunc('7')">7</button>
<button onclick="calFunc('8')">8</button>
<button onclick="calFunc('9')">9</button>
<button onclick="calFunc('-')" class="op-btn">-</button>
<button onclick="calFunc('4')">4</button>
<button onclick="calFunc('5')">5</button>
<button onclick="calFunc('6')">6</button>
<button onclick="calFunc('*')" class="op-btn">*</button>
<button onclick="calFunc('1')">1</button>
<button onclick="calFunc('2')">2</button>
<button onclick="calFunc('3')">3</button>
<button onclick="calFunc('/')" class="op-btn">/</button>
<button onclick="calFunc('0')">0</button>
<button onclick="calFunc('.')">.</button>
<button onclick="executeEqual()">=</button>
<button onclick="clearDisplay()" class="op-btn">C</button>
</div>
</div>
<script src="temp.js"></script>
</body>
</html>
temp.js code :
======================================================
===================================
Change the
background color
Element Selectors
2. getElementClassName( )
Html collections don’t have forEach() method. Typecase the html collection
as an array
3.getElementByTagName( )
another way
4. Query selector ( ) - always selects the first element
5 Query selector( ) -
Dom Navigation :
2.LastElementChild
3.nextElementSibling
Similarly for the prevElementSibling
6. Children
Add & Change Html Element
use of the
prepend
Mouse Events
When hover on the buttom , when click on the buttom , when mouse out of
the bottom
😉
<div id="mybox">
</div>
<script src="temp.js"></script>
</body>
</html>
const mybox = document.getElementById("mybox");
const moveAmount = 100;
let x = 0;
let y = 0;
🤦
document.addEventListener("keydown", event => {
mybox.textContent = " ";
mybox.style.backgroundColor = "tomato";
});
😉
document.addEventListener("keyup", event => {
mybox.textContent = " ";
mybox.style.backgroundColor = "lightblue";
});
document.addEventListener("keydown", event => {
if (event.key.startsWith("Arrow")) {
event.preventDefault(); // prevent the default behaviour of the key
switch (event.key) {
case "ArrowUp":
y -= moveAmount;
break;
case "ArrowDown":
y += moveAmount;
break;
case "ArrowLeft":
x -= moveAmount;
break;
case "ArrowRight":
x += moveAmount;
break;
}
mybox.style.top = `${y}px`;
mybox.style.left = `${x}px`;
}
});
================================================================
============================================
Hide / Show Html Element :
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#myButton{
font-size: 2rem;
}
</style>
</head>
<body>
<button id="myButton">hide</button>
<img id="myImg"
src="https://img-cdn.pixlr.com/image-generator/history/65bb506dcb310754719cf81f/e
de935de-1138-4f66-8ed7-44bd16efc709/medium.webp" width="400px"><br>
<script src="temp.js"></script>
</body>
</html>
======================================================
=========================================
Node Lists
MouseOver + MouseOut
When hovering over these the color of the button changes
NodeLIst are static the buttons 5 which is added that won’t be automatically
added
we need to add this manually. So that why we assigned the button by the let
not by the const
So that we can’t reassign it, We can again add this by the querySelectorAll(
.myButtons) // (class)
Check after the updation Console.log(buttons) // nodeList has the 5 buttons
now
buttons are clicked and are removed Like the second button is clicked and
removed
The buttons are removed from the dom not from the node list . NodeLIst has
still the buttons
We need to update that manually
After
doing it manually removed from the both the dom and the node list
The code is >
======================================================
=================================================
Class List :
Add the new introduced class or may joined to the current buttons or the
element
😡
Verification of the disabled class. Clicked on the button disabled ok , again
click execute the if and sets the button +=
On the 4 buttons 1. Hover 2. Clicked
when
class is disabled append the emoji
======================================================
==============================
Rock - Paper - Scissors
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body {
font-family: Arial, sans-serif;
font-weight: bold;
margin: 0;
display: flex;
flex-direction: column;
align-items: center;
}
h1{
font-size: 3.5rem;
color: hsl(0,0%,20%);
}
.choices{
margin-bottom: 30px;
}
.choices button{
font-size: 7.5rem;
min-width: 160px;
border-radius: 250px;
background-color: hsl(200,100%,50%);
cursor: pointer;
transition: background-color 0.5s ease;
}
.choices button:hover{
background-color: hsl(200,100%,70%);
}
#playerDisplay, #computerDisplay{
font-size: 2.5rem;
}
#resultDisplay{
font-size:5rem;
}
.scoreDisplay{
font-size: 2rem;
}
.greenText,#playerScoreDisplay{
color: #52FA31;
}
.redText,#computerScoreDisplay{
color:#FD2222;
}
</style>
</head>
<body>
<h1>Rock - Paper - Scissors</h1>
👊
<div class="choices">
✋
<button onclick="playGame('rock')"> </button>
<button onclick="playGame('paper')"> </button>
<button onclick="playGame('scissors')">✌</button>
</div>
<div id="playerDisplay">PLAYER: </div>
<div id="computerDisplay">COMPUTER: </div>
<div id="resultDisplay">IT'S A TIE!</div>
<div class="scoreDisplay">Player Score:
<span id="playerScoreDisplay">0</span>
</div>
<div class="scoreDisplay">Computer Score:
<span id="computerScoreDisplay">0</span>
</div>
<script src="temp.js"></script>
</body>
</html>
================================================================
========================
IMAGE SLIDER
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.slider{
position: relative;
width: 100%;
margin: auto;
overflow: hidden;
}
.slider img{
width: 100%;
display: none;
}
img.displaySlide{
display: block;
}
.slider button{
position: absolute; <!-- file:///D:/C++%20CODE/FRONTEND/boxmodel.html -->
top: 50%;
transform: translateY(-50%);
font-size: 2rem;
padding: 10px 15px;
background-color: hsla(0,0%,0%,0.5);
color: white;
border: none;
cursor: pointer;
}
.prev{
left: 0;
}
.next{
right: 0;
}
</style>
</head>
<body>
<div class="slider">
<div class="slides">
<img
src="https://hips.hearstapps.com/hmg-prod/images/2019-honda-civic-sedan-1558453497.jpg?crop=1xw:0.999772778913
8833xh;center,top&resize=980:*">
<img
src="https://hips.hearstapps.com/hmg-prod/images/2019-mercedes-benz-e-class-coupe-1548703839.jpg?crop=1xw:0.99
97727789138833xh;center,top&resize=980:*">
<img
src="https://hips.hearstapps.com/hmg-prod/images/2019-hyundai-kona-1548195339.jpg?crop=1xw:0.9997727789138833x
h;center,top&resize=980:*">
</div>
<button class="prev" onclick="prevSlide()">❮</button>
<button class="next" onclick="nextSlide()">❯</button>
</div>
<script src="temp.js"></script>
</body>
</html>
JavaScript code
const slides = document.querySelectorAll(".slides img");
let slideIndex = 0;
let intervalId = null;
document.addEventListener("DOMContentLoaded", initlizeSlider);
function initlizeSlider() {
if (slides.length > 0) {
slides[slideIndex].classList.add("displaySlide");
intervalId = setInterval(nextSlide, 3000);
}
}
function showSlide(index) {
if (index >= slides.length) {
slideIndex = 0;
} else if (index < 0) {
slideIndex = slidelength - 1;
}
slides.forEach(slide => {
slide.classList.remove("displaySlide");
});
slides[slideIndex].classList.add("displaySlide");
}
function prevSlide() {
clearInterval(intervalId);
slideIndex--;
showSlide(slideIndex);
}
function nextSlide() {
slideIndex++;
showSlide(slideIndex);
}
======================================================
======================================
CAll Back Hell
Tasks outputs in random order but are executed in the correct order : TASK
BASED ASYNCHRONOUS PROGRAMMING
function task1() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (1) {
resolve("task1");
} else {
reject("Not 1");
}
}, 2500);
})
}
function task2() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (1) {
resolve("task2");
} else {
reject("Not2");
}
}, 1500);
})
}
function task3() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (1) {
resolve("task3");
} else {
reject("Not 3");
}
}, 3000);
})
}
function task4() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (1) {
resolve("task4");
} else {
reject("Not 4");
}
}, 2000);
})
}
task1().then(
value => {
console.log(value);
return task2()
})
.then(
value => {
console.log(value);
return task3()
})
.then(
value => {
console.log(value);
return task4()
})
.then(
value => {
console.log(value);
console.log("All tasks are completed");
})
.catch((error) => {
console.error("An error occured: ", error);
})
task1
task2
task3
task4
Async / Await
JSON
makes a single long
string to work with
COUNTER =>
Open Modal :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Centered Box</title>
</head>
<div
</div>
<div
</div>
</div>
<!-- Centered box -->
<img
src="https://plus.unsplash.com/premium_photo-1678197937465-bdbc4ed95815?fm=jpg&q=6
0&w=3000&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8NXx8cGVyc29ufGVufDB8fD
B8fHww"
<button onclick="openModal()"
Profile</button>
Me</button>
</div>
</div>
</div>
<style>
@layer utilities {
@keyframes wiggle {
0%,
100% {
25% {
50% {
75% {
transform: translate(0, 100px) rotate(270deg);
100% {
.animate-wiggle {
</style>
<div
class="modal fixed top-0 left-0 w-full h-full bg-black bg-opacity-50 flex items-center
justify-center text-white hidden z-10">
<div
<button onclick="openModal()"
</div>
<button
<img src="https://img.icons8.com/ios-filled/50/ffffff/whatsapp.png">
</button>
<button
</button>
<button
<img src="https://img.icons8.com/ios-filled/50/ffffff/instagram-new.png">
</button>
<button
<img src="https://img.icons8.com/ios-filled/50/ffffff/facebook-new.png">
</button>
<button
<img src="https://img.icons8.com/ios-filled/50/ffffff/telegram.png">
</button>
</div>
</div>
</div>
</div>
</div>
<script>
function openModal() {
document.querySelector('.modal').classList.toggle('hidden');
if (event.target.classList.contains('modal')) {
openModal();
</script>
</body>
</html>
PASSWORD GENERATOR
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Password generator</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<div class="container">
<h1>Password Generator</h1>
<div class="display-container">
<button class="copy-btn">
<span data-copyMsg></span>
</button>
</div>
<div class="input-container">
<div class="length-container">
<p>Password Length</p>
<p data-length>0</p>
</div>
<div class="slider-container">
</div>
<!--checkboxes -->
<div>
</div>
<div>
</div>
<div>
<div>
</div>
<div class="strength-container">
<p>Strength</p>
<div data-indicator></div>
</div>
</div>
<script>
let checkbox = 1;
handleSlider();
function handleSlider() {
inputSlider.value = passwordLength;
lengthDisplay.innerText = passwordLength;
function setIndicator(color) {
indicator.style.backgroundColor = color;
indicator.style.boxShadow = `0px 0px 12px 1px ${color}`;
function generateRandomNumber() {
function generateLowercase() {
function generateUpperCase() {
function symbolGenerator() {
function calcStrength() {
setIndicator("green");
setIndicator("orange");
} else {
setIndicator("red");
try {
await navigator.clipboard.writeText(passwordDisplay.value);
copyMsg.innerText = "Copied";
catch (e) {
copyMsg.innerText = "Failed";
}
copyMsg.classList.add("active");
setTimeout(() => {
copyMsg.classList.remove("active");
}, 2000);
passwordLength = e.target.value;
handleSlider();
});
copyBtn.addEventListener("click", () => {
if (passwordDisplay.placeholder) {
copyContent();
});
function shufflePassword(array) {
}
let str = "";
return str;
function handleCheckBoxChange() {
checkBox = 0;
allCheckBox.forEach((checkbox) => {
if (checkbox.checked) {
checkBox++;
});
passwordLength = checkBox;
handleSlider();
allCheckBox.forEach((checkbox) => {
checkbox.addEventListener('change', handleCheckBoxChange);
})
generateBtn.addEventListener('click', () => {
passwordLength = checkBox;
password = "";
if (upperCase.checked) {
funArr.push(generateUpperCase);
if (lowerCase.checked) {
funArr.push(generateLowercase);
if (number.checked) {
funArr.push(generateRandomNumber);
if (symbol.checked) {
funArr.push(symbolGenerator);
password += funArr[i]();
password += rand();
password = shufflePassword(Array.from(password));
passwordDisplay.value = password;
calcStrength();
});
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="flex">
<script>
function switchTab(tabNumber) {
// Add active class to the clicked tab and the corresponding tab content
document.getElementById('tab' + tabNumber).classList.remove('hidden');
switchTab(1);
</script>
</body>
</html>