0% found this document useful (0 votes)
3 views126 pages

Javascript Learning

The document outlines various types of events in JavaScript, including mouse, keyboard, form, drag and drop, clipboard, touch, focus, window, media, and miscellaneous events. It also explains how to attach event listeners using addEventListener and provides examples of JavaScript functions and methods for manipulating strings and arrays. Additionally, it includes code snippets for creating a digital clock and a stopwatch project using HTML, CSS, and JavaScript.

Uploaded by

Åmån Råj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views126 pages

Javascript Learning

The document outlines various types of events in JavaScript, including mouse, keyboard, form, drag and drop, clipboard, touch, focus, window, media, and miscellaneous events. It also explains how to attach event listeners using addEventListener and provides examples of JavaScript functions and methods for manipulating strings and arrays. Additionally, it includes code snippets for creating a digital clock and a stopwatch project using HTML, CSS, and JavaScript.

Uploaded by

Åmån Råj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 126

1.

Mouse Events

These events are triggered by actions of the mouse:

●​ click: Triggered when the user clicks on an element.


●​ dblclick: Triggered when the user double-clicks an element.
●​ mousedown: Triggered when the mouse button is pressed down.
●​ mouseup: Triggered when the mouse button is released.
●​ mousemove: Triggered when the mouse pointer moves over an
element.
●​ mouseover: Triggered when the mouse pointer enters the boundaries
of an element.
●​ mouseout: Triggered when the mouse pointer leaves the boundaries
of an element.
●​ mouseenter: Similar to mouseover but does not bubble.
●​ mouseleave: Similar to mouseout but does not bubble.
●​ contextmenu: Triggered when the user opens a context menu (usually
a right-click).

2. Keyboard Events

These events are triggered by keyboard actions:

●​ keydown: Triggered when a key is pressed down.


●​ keyup: Triggered when a key is released.

3. Form Events

These are related to form elements like <input> or <select>:

●​ focus: Triggered when an element gains focus.


●​ blur: Triggered when an element loses focus.
●​ input: Triggered when the value of an input or textarea is changed.
●​ change: Triggered when the user commits a change to an input or
select element.
●​ submit: Triggered when a form is submitted.
●​ reset: Triggered when a form is reset.
●​ select: Triggered when the user selects text inside an input or
textarea.

4. Drag and Drop Events

Used for drag-and-drop interactions:

●​ drag: Triggered when an element is being dragged.


●​ dragstart: Triggered when the user starts dragging an element.
●​ dragend: Triggered when the user stops dragging an element.
●​ dragenter: Triggered when a dragged item enters a drop zone.
●​ dragover: Triggered when a dragged item is over a drop zone.
●​ dragleave: Triggered when a dragged item leaves a drop zone.
●​ drop: Triggered when a dragged item is dropped on a drop zone.

5. Clipboard Events

Triggered by copy-paste actions:

●​ copy: Triggered when content is copied.


●​ cut: Triggered when content is cut.
●​ paste: Triggered when content is pasted.

6. Touch Events (for Mobile/Touch Devices)

Triggered by touch actions on touchscreens:

●​ touchstart: Triggered when a touch starts.


●​ touchmove: Triggered when a finger moves across the screen.
●​ touchend: Triggered when a touch ends.
●​ touchcancel: Triggered when a touch is interrupted (e.g., by a system
alert).

7. Focus and Window Events

Events related to focus, scrolling, resizing, etc.:

●​ resize: Triggered when the browser window is resized.


●​ scroll: Triggered when the user scrolls an element.
●​ focus: Triggered when an element gets focus.
●​ blur: Triggered when an element loses focus.
●​ load: Triggered when an element has loaded.
●​ unload: Triggered when the page is unloaded.
●​ beforeunload: Triggered before the page is unloaded (used for
warning dialogs).
●​ error: Triggered when an error occurs (e.g., a failed image load).

8. Media Events

Used for audio and video elements:

●​ play: Triggered when media starts playing.


●​ pause: Triggered when media is paused.
●​ ended: Triggered when media playback ends.
●​ volumechange: Triggered when the volume is changed.
●​ timeupdate: Triggered when the playback position changes.

9. Miscellaneous Events

Other useful events:

●​ wheel: Triggered when the user scrolls using a mouse wheel.


●​ animationstart: Triggered when a CSS animation starts.
●​ animationend: Triggered when a CSS animation ends.
●​ transitionend: Triggered when a CSS transition completes.

Event Listeners

You can attach these events using addEventListener:

javascript

Copy code

element.addEventListener('click', () => console.log('Clicked!'));

element.addEventListener('mouseover', () => console.log('Hovered!'));

element.addEventListener('keydown', (event) => console.log(`Key pressed:


${event.key}`))

More about the Html : && css


Span is a inline container

Div is a block level container

Css box property fixed box2 and box1


Css Positions

Fixed in the center of the image in the middle of the it by the css property
Combinators of the css :

Pseudo classes in the css :


any thing
which is currently not hovered over and not hovered over

DesCription List :
To create the html form :
Formatting types ;
To apply css in the html

To add the font from the folder of the project

------------------------------------------------------------------------------
------------------------------------------------------------------------------
---

New things here for the javascript

Use of the then in the promise


https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_w
eb/JavaScript_basics

"cmd": ["node", "$file"],

"selector": "source.js",

"working_dir": "$file_path",

"shell_cmd": "node \"$file\" < \"$file_path/input.txt\" >


\"$file_path/output.txt\""

This is code runTheJsFile.sublime-build

Install the extension CONSOLE NINZA for the vs code


This is a way to write the inline js code.

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))

.split(“ “) This method will make the array of string.

.join(“ “) after the split(“ “).join(“ “) will be back to the string.

SLICE AND JOIN METHODS :

1. Remove Specific Characters

let str = "hello, world";

let result = str.split(",").join(""); // Removes the comma

console.log(result); // "hello world"


2. Replace Characters

let str = "hello, world";

let result = str.split(",").join(";"); // Replaces the comma with a semicolon

console.log(result); // "hello; world"

3. Add a Character Between Words

let str = "hello world";

let result = str.split(" ").join("-"); // Joins words with a hyphen

console.log(result); // "hello-world"

4. Reverse Words in a Sentence

let str = "hello world";

let result = str.split(" ").reverse().join(" "); // Reverses the order of words

console.log(result); // "world hello"

5. Convert All Spaces to Another Separator

let str = "hello world this is JS";

let result = str.split(" ").join("_"); // Converts spaces to underscores

console.log(result); // "hello_world_this_is_JS"

6. Remove All Whitespace

let str = "hello world";


let result = str.split(/\s+/).join(""); // Removes all spaces

console.log(result); // "helloworld"

7. Replace Multiple Spaces with a Single Space

let str = "hello world";

let result = str.split(/\s+/).join(" "); // Converts multiple spaces to a single space

console.log(result); // "hello world"

8. Extract and Join Specific Parts

let str = "apple,banana,grape";

let result = str.split(",").reverse().join(" | "); // Reverse the order and join with a pipe

console.log(result); // "grape | banana | apple"

9. Join Array of Strings into a Single String

let arr = ["apple", "banana", "grape"];

let result = arr.join(", "); // Joins array elements with a comma and a space

console.log(result); // "apple, banana, grape"

10. Convert an Array of Numbers into a String

let numbers = [1, 2, 3, 4, 5];

let result = numbers.join("-"); // Joins numbers with hyphens

console.log(result); // "1-2-3-4-5"
.include() it checks the substr is present or not .. returns the True / False

.trim() method remove the white spaces

Template Literals
Switch Case Basic

Space named key : Oops

In this scenario We can’t use the .dot operator here


This can be accessed inside using the dot operator

Using this We don’t get the error


To Delete the object

For each loop to access the key


With the values

Arguments with the function


Function Assignment
Hoisting in the javaScript

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

Arrow functions with the object

IMP : A arrow function can ‘t be used with the this keyword (because it
assumes the windows object i.e {empty})

So we can only use the function() method in the class def


Object function
More advance and cleaner way to use the function+this in the class

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

> keeps the count of the users we create


Here This is refers to the laptop i.e laptop.cpu == this.cpu

This keyword refers to the current object. It can access the property of an
object
Laptop1.compare(Laptop2) this is how it’ll work

put comma at the end of the


compare func.
…parameter used with the This keyword

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

Function introduced in the Array of the objects

.shift() method remove the first value

.unshift(x) method inserts the elements to the first value

Splice working method


splice(index,no_of_element_to_remove);

We can also inserts elements in the given position we mentioned in the


splice

Ways to initialize the Array


allNames will have myNames+ “d”

Different types of the for Each loops in the js


Use of the entries() in the for-each loop

This prints the index as well

A another way
If we want to skip the element

Array of the string using the split


Inbuild forEach Method

Even this is also cool but only for the single variable

Printing with indexes


Use of the Filter

Apply filter and forEach at a time


Use case of the Map

To edit the array in shortcode


Output of this

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

To find the in the set


Use of the Callback () function A(B) first the A function will be executed
and then B also called the Asynchronous

The html code


forEach & function & callBack

Function Expressions
Use case of the Super keyword
super.useParentMethod(arg1,arg2)

Getters and Setters


Sort in the js

(b-a) denotes the dec sort and (a-b) denotes ascending

Sort with lexicographical order


Suffle Algorithm

Closure
Used the Get method to access the property of the Inner Function
SetTimeOut

ClearTimeout and alert


Digital-Clock - PROJECT 1

// 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>

const display = document.getElementById("display")​


let timer = null;​
let startTime = 0;​
let stopTime = 0;​
let isRun = false;​

function start() {​
if (!isRun) {​
startTime = Date.now() - stopTime;​
timer = setInterval(update, 10);​
isRun = true;​
}​
}​

function stop() {​
if (isRun) {​
clearInterval(timer);​
stopTime = Date.now() - startTime;​
isRun = false;​
}​
}​

function reset() {​
clearInterval(timer);​
startTime = 0;​
stopTime = 0;​
isRun = false;​
display.textContent = "00:00:00:00";​
}​

function update() {​
const currTime = Date.now();​
stopTime = currTime - startTime;​
let h = Math.floor(stopTime / (1000 * 60 * 60));​
let m = Math.floor((stopTime / (1000 * 60)) % 60);​
let s = Math.floor((stopTime / 1000) % 60);​
let ms = Math.floor((stopTime % 1000) / 10);​

h = String(h).padStart(2, "0");​
m = String(m).padStart(2, "0");​
s = String(s).padStart(2, "0");​
ms = String(ms).padStart(2, "0");​

display.textContent = `${h}:${m}:${s}:${ms}`;​
}

======================================================
===========================================
ES6 module :
Set the html file to type = “module”

Synchronous & Asynchronous

This code is Async


This code is Sync

Try and Catch and Error :


Successfully reaching the end of the program
Instead use the console.error(error); in catch to highlight the error it still
reached the end.

[1/0] dividend = 1, divisor = 0

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 :

const display = document.getElementById("display");​



function calFunc(value) {​
display.value += value;​
}​

function executeEqual() {​
try {​
display.value = eval(display.value);​
} catch (error) {​
display.value = "Error";​
}​
}​

function clearDisplay() {​
display.value = "";​
}

======================================================
===================================

DOM : DOCUMENT OBJECT

​ ​ ​ ​ ​ ​ ​ ​ ​ 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

Similarly for the


FirstElementChild

3.nextElementSibling
Similarly for the prevElementSibling

5. ParentElement- whichever element i’ll select it will select the parent of it

6. Children
Add & Change Html Element
use of the

prepend

>Insert between = insertBefore( newElement , currentElement ) >


using the query selector
>Remove the html element 1. Select the parent of the element by the Id 2.
Pass the element & pass it as argument
This is the way to remove the element of the coconut which was created

Mouse Events
When hover on the buttom , when click on the buttom , when mouse out of
the bottom

Holding and release the buttom


before hold and after hold while
holding

Block Moving Project


<!DOCTYPE html>​
<html lang="en">​
<head>​
<style>​
body{​
margin: 0;​
}​
#mybox{​
background-color:lightblue;​
width: 200px;​
height: 200px;​
font-size: 7.5rem;​
display: flex;​
justify-content: center;​
align-items: center;​
position: relative;​
}​
</style>​
</head>​
<body>​

😉
<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 :

after clicking on the hide button

<!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>

const myButton = document.getElementById("myButton");​


const myImg = document.getElementById("myImg");​
myButton.addEventListener("click", event => {​
if (myImg.style.visibility === "hidden") {​
myImg.style.visibility = "visible";​
myButton.textContent = "hide";​
} else {​
myImg.style.visibility = "hidden";​
myButton.textContent = "Show"​
}​
});

======================================================
=========================================

Node Lists

can be seen as the prototype


These eventListerners listen to the events When buttons are clicked the
color are changed
this .querySelectorAll(.myButtons) represent all these buttons of the html

MouseOver + MouseOut
When hovering over these the color of the button changes

A new button was added

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

4. Remove the buttons

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

after addition after remove

Mouseover and Mouseout


To use the toggle 1. Just change the add & remove with the toggle

Replace this old class with the new class

😡
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>

const choices = ["rock", "paper", "scissors"]​


const playerDisplay = document.getElementById("playerDisplay");​
const computerDisplay = document.getElementById("computerDisplay");​
const resultDisplay = document.getElementById("resultDisplay");​

const playerScoreDisplay = document.getElementById("playerScoreDisplay");​
const computerScoreDisplay = document.getElementById("computerScoreDisplay");​
let playerScore = 0;​
let computerScore = 0;​

const playGame = (playerChoice) => {​
const computerChoice = choices[Math.floor(Math.random() * 3)];​
let result = "";​
if (playerChoice === computerChoice) {​
result = "IT'S A TIE!";​
} else {​
switch (playerChoice) {​
case "rock":​
result = (computerChoice === "scissors") ? "YOU WIN!" : "YOU LOSE!";​
break;​
case "paper":​
result = (computerChoice === "rock") ? "YOU WIN!" : "YOU LOSE!";​
break;​
case "scissors":​
result = (computerChoice === "paper") ? "YOU WIN!" : "YOU LOSE!";​
break;​
}​
}​
playerDisplay.textContent = `PLAYER : ${playerChoice}`;​
computerDisplay.textContent = `Computer : ${computerChoice}`;​
resultDisplay.textContent = result;​
resultDisplay.classList.remove("greenText", "redText");​
switch (result) {​
case "YOU WIN!":​
resultDisplay.classList.add("greenText");​
playerScore++;​
playerScoreDisplay.textContent = playerScore;​
break;​
case "YOU LOSE!":​
resultDisplay.classList.add("redText");​
computerScore++;​
computerScoreDisplay.textContent = computerScore;​
break;​
}​
}​

================================================================
========================

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()">&#10094</button>​
<button class="next" onclick="nextSlide()">&#10095</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

Tasks outputs in correct order as expected : TASKS BASED


SYNCHRONOUS PROGRAMMING
Promises

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

All tasks are completed

Async / Await

JSON
makes a single long
string to work with

And json.parse( ) converts string to the json object

COUNTER​ =>
Open Modal :
<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Centered Box</title>

<script src="https://cdn.tailwindcss.com"></script> <!-- Make sure Tailwind is loaded -->

</head>

<body class="flex items-center justify-center h-screen bg-black">

<!-- Background circles -->

<div class="absolute inset-5 -z-10 overflow-hidden">

<!-- Circle 1 green-->

<div

class="absolute bottom-[150px] right-[150px] w-[300px] h-[300px] rounded-full


bg-green-500 animate-wiggle opacity-80 backdrop-blur-2xl shadow-2xl
shadow-green-500/90 ">

</div>

<!-- Circle 2 blue-->

<div

class="absolute top-[100px] left-[150px] w-[300px] h-[300px] rounded-full bg-blue-600


animate-wiggle opacity-50 backdrop-blur-2xl shadow-2xl shadow-blue-500/90 shadow-lg
shadow-blue-700/70">

</div>

</div>
<!-- Centered box -->

<div class="w-[450px] h-[500px] text-white flex flex-col items-center justify-center


rounded-lg shadow-2xl backdrop-blur-lg overflow-hidden z-10 border-2 border-white
border-opacity-50">

<div class="flex flex-col items-center justify-center">

<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"

class="w-48 h-48 object-cover rounded-full mb-8">

<h1 class="mb-[25px] text-4xl font-bold text-center">Love Babber</h1>

<p class="text-lg text-center">Founder, Code Help</p>

<div class="flex flex-row space-x-8 mt-8">

<button onclick="openModal()"

class="py-2 px-6 rounded border-2 hover:bg-gray-500 transition-all duration-300


ease-in-out">Share my

Profile</button>

<button class="py-2 px-6 rounded border-2 hover:bg-gray-500 transition-all


duration-300 ease-in-out">Follow

Me</button>

</div>

</div>
</div>

<!-- Tailwind CSS custom animations -->

<style>

@layer utilities {

@keyframes wiggle {

0%,

100% {

transform: translate(0, 0) rotate(0deg);

25% {

transform: translate(100px, 0) rotate(90deg);

50% {

transform: translate(100px, 100px) rotate(180deg);

75% {
transform: translate(0, 100px) rotate(270deg);

100% {

transform: translate(0, 0) rotate(360deg);

.animate-wiggle {

animation: wiggle 4s infinite;

</style>

<!-- modal here -->

<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

class="bg-black bg-opacity-50 backdrop-blur-md w-[530px] h-[230px] rounded-2xl


border-2 border-white border-opacity-50">
<div class="flex flex-row mr-5 justify-between">

<h2 class="p-3 px-5 text-2xl text-white">Share My Profile</h2>

<button onclick="openModal()"

class="rounded-full text-3xl text-white hover:bg-gray-500 transition-all duration-300


w-10 h-10 flex items-center justify-center mt-2">&times;</button>

</div>

<div class="w-full h-[1px] bg-white px-4 ">

<h3 class="py-5 px-2">Share this via</h3>

<div class="flex flex-row space-x-10 px-4 mt-3">

<button

class="py-2 px-2 rounded-full border-2 border-green-500 hover:bg-green-800


bg-opacity-90 backdrop-blur-lg transition-all duration-300 ease-in-out hover:shadow-lg">

<img src="https://img.icons8.com/ios-filled/50/ffffff/whatsapp.png">

</button>

<button

class="py-2 px-2 rounded-full border-2 border-blue-500 hover:bg-blue-600


bg-opacity-90 backdrop-blur-lg transition-all duration-300 ease-in-out hover:shadow-lg">
<img src="https://img.icons8.com/ios-filled/50/ffffff/twitter.png">

</button>

<button

class="py-2 px-2 rounded-full border-2 border-red-500 hover:bg-red-800


bg-opacity-90 backdrop-blur-lg transition-all duration-300 ease-in-out hover:shadow-lg">

<img src="https://img.icons8.com/ios-filled/50/ffffff/instagram-new.png">

</button>

<button

class="py-2 px-2 rounded-full border-2 border-blue-800 hover:bg-blue-900


bg-opacity-90 backdrop-blur-lg transition-all duration-300 ease-in-out hover:shadow-lg">

<img src="https://img.icons8.com/ios-filled/50/ffffff/facebook-new.png">

</button>

<button

class="py-2 px-2 rounded-full border-2 border-blue-300 hover:bg-blue-600


bg-opacity-90 backdrop-blur-lg transition-all duration-300 ease-in-out hover:shadow-lg">

<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');

window.onclick = function (event) {

if (event.target.classList.contains('modal')) {

openModal();

</script>

</body>

</html>
PASSWORD GENERATOR

<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Password generator</title>

<script src="https://cdn.tailwindcss.com"></script>

</head>

<body>

<div class="container">

<h1>Password Generator</h1>

<div class="display-container">

<input readonly placeholder="Password" class="data-display">

<button class="copy-btn">

<span data-copyMsg></span>

<img src="copyVector.svg" width="23" height="23">

</button>

</div>

<div class="input-container">

<!-- password length section -->

<div class="length-container">
<p>Password Length</p>

<p data-length>0</p>

</div>

<!-- slider -->

<div class="slider-container">

<input type="range" min="1" max="20" class="slider" step="1" data-lenghtSlider>

</div>

<!--checkboxes -->

<div>

<input type="checkbox" id="uppercase"> <label


for="uppercase">Uppercase</label><br>

</div>

<div>

<input type="checkbox" id="lowercase"> <label


for="lowercase">Lowercase</label><br>

</div>

<div>

<input type="checkbox" id="number"> <label for="number">Numbers</label><br>


</div>

<div>

<input type="checkbox" id="symbol"> <label for="symbol">Symbol</label><br>

</div>

<!-- strength meter -->

<div class="strength-container">

<p>Strength</p>

<div data-indicator></div>

</div>

<!-- generate password button -->

<button data-generate>Generate Password</button>

</div>

<script>

const inputSlider = document.querySelector("[data-lenghtSlider]");

const lengthDisplay = document.querySelector("[data-length]");

const allCheckBox = document.querySelectorAll("input[type='checkbox']");

const passwordDisplay = document.querySelector(".data-display");


const copyMsg = document.querySelector("[data-copyMsg]");

const indicator = document.querySelector("[data-indicator]");

const generateBtn = document.querySelector("[data-generate]");

const upperCase = document.querySelector("#uppercase");

const lowerCase = document.querySelector("#lowercase");

const number = document.querySelector("#number");

const symbol = document.querySelector("#symbol");

const copyBtn = document.querySelector(".copy-btn");

const symbols = "!@#$%^&*(){}[]=<>/,.|~?";

let password = "";

let passwordLength = 10;

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 getRandomInt(min, max) {

return Math.floor(Math.random() * (max - min) + min);

function generateRandomNumber() {

return getRandomInt(0, 9);

function generateLowercase() {

return String.fromCharCode(getRandomInt(97, 123));

function generateUpperCase() {

return String.fromCharCode(getRandomInt(65, 91));

function symbolGenerator() {

return symbols[getRandomInt(0, symbols.length)];

function calcStrength() {

let hasUpper = false;

let hasLower = false;

let hasNumber = false;


let hasSymbol = false;

if (upperCase.checked) hasUpper = true;

if (lowerCase.checked) hasLower = true;

if (number.checked) hasNumber = true;

if (symbol.checked) hasSymbol = true;

if (hasUpper && hasLower && (hasNumber || hasSymbol) && passwordLength >= 8) {

setIndicator("green");

} else if ((hasUpper || hasLower) && (hasNumber || hasSymbol) && passwordLength >=


6) {

setIndicator("orange");

} else {

setIndicator("red");

async function copyContent() {

let text = passwordDisplay.value;

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);

inputSlider.addEventListener("input", (e) => {

passwordLength = e.target.value;

handleSlider();

});

copyBtn.addEventListener("click", () => {

if (passwordDisplay.placeholder) {

copyContent();

});

function shufflePassword(array) {

// Fisher yates algorithm can be applied on the array

for (let i = array.length - 1; i > 0; i--) {

const j = Math.floor(Math.random() * (i + 1));

[array[i], array[j]] = [array[j], array[i]];

}
let str = "";

array.forEach((x) => (str += x));

return str;

function handleCheckBoxChange() {

checkBox = 0;

allCheckBox.forEach((checkbox) => {

if (checkbox.checked) {

checkBox++;

});

if (passwordLength < checkBox) {

passwordLength = checkBox;

handleSlider();

allCheckBox.forEach((checkbox) => {

checkbox.addEventListener('change', handleCheckBoxChange);

})

generateBtn.addEventListener('click', () => {

if (checkBox <= 0) return;


if (passwordLength < checkBox) {

passwordLength = checkBox;

password = "";

let funArr = [];

if (upperCase.checked) {

funArr.push(generateUpperCase);

if (lowerCase.checked) {

funArr.push(generateLowercase);

if (number.checked) {

funArr.push(generateRandomNumber);

if (symbol.checked) {

funArr.push(symbolGenerator);

for (let i = 0; i < funArr.length; i++) {

password += funArr[i]();

for (let i = 0; i < passwordLength - funArr.length; i++) {


let rand = funArr[getRandomInt(0, funArr.length)];

password += rand();

// shuffle the password

password = shufflePassword(Array.from(password));

passwordDisplay.value = password;

calcStrength();

});

</script>

</body>

</html>

TAB CHANGING EXAMPLE


<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Tab Switching Example</title>

<!-- Tailwind CSS CDN -->

<script src="https://cdn.tailwindcss.com"></script>

</head>

<body class="flex">

<!-- Tabs -->

<div class="tab pr-5" onclick="switchTab(1)">Tab 1</div>

<div class="tab pr-5" onclick="switchTab(2)">Tab 2</div>

<!-- Tab Content -->

<div id="tab1" class="tab-content hidden">TAB 1 CONTENT </div>

<div id="tab2" class="tab-content hidden">TAB 2 CONTENT </div>

<script>
function switchTab(tabNumber) {

// Get all the tabs and tab content

const tabs = document.querySelectorAll('.tab');

const tabContents = document.querySelectorAll('.tab-content');

// Remove active class from all tabs and tab contents

tabs.forEach(tab => tab.classList.remove('bg-blue-600', 'text-white'));

tabContents.forEach(content => content.classList.add('hidden'));

// Add active class to the clicked tab and the corresponding tab content

tabs[tabNumber - 1].classList.add('bg-blue-600', 'text-white');

document.getElementById('tab' + tabNumber).classList.remove('hidden');

// Initialize first tab as active

switchTab(1);

</script>

</body>

</html>

This is the smaller code for the tab exchanging

You might also like