0% found this document useful (0 votes)
4 views

Java Script

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Script

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 36

========================= INERACTIVE WEB PAGES ===================

===================================================================================
=========================
<button id="fade-btn">Fade</button>
<div id="fade-box" style="width: 100px; height: 100px; background-color: lightblue;
opacity: 1;"></div>

<script>
const selectors = {
btn: document.getElementById("fade-btn"),
box: document.getElementById("fade-box")
};

const startAnimation = (elementToAnimate) => {


let opacity = 1;
let direction = -0.1;

const intervalId = setInterval(() => {


opacity += direction;
elementToAnimate.style.opacity = opacity;
if (opacity >= 0) {
direction *= 0.1;
}
}, 10);
};

selectors.btn.addEventListener("click", () => startAnimation(selectors.box));


</script>

===================================================================================
================================
<button id="pulse-btn">Pulse</button>
<style>
#pulse-btn {
width: 100px;
height: 50px;
background-color: lightseagreen;
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
position: relative;
}
</style>
<script>
const selectors = {
btn: document.getElementById("pulse-btn") // Fixed semicolon to comma
};

const startAnimation = (elementToAnimate) => {


let scale = 1; // Starting scale
let direction = 0.01; // Change in scale per interval

const intervalId = setInterval(() => {


scale += direction;
elementToAnimate.style.transform = `scale(${scale})`; // Corrected syntax

// Reverse direction when reaching the maximum scale


if (scale >= 1.5) {
direction = -0.01;
} else if (scale <= 1) {
direction = 0.01;
}
}, 20); // Adjusted interval for smoother animation
};

selectors.btn.addEventListener("click", () => startAnimation(selectors.btn));


</script>

===================================================================================
=============================
const selectors = {
btn: document.getElementById("bounce-color-btn"), // Fixed ID
box: document.getElementById("bounce-color-box")
};

const startAnimation = (elementToAnimate) => {


let position = 0;
let direction = 1;
const random = Math.round(Math.random() * 360); // Random hue for color
const intervalId = setInterval(() => {
position += direction;
elementToAnimate.style.top = position + 'px';

// Bounce logic and color change


if (position >= 100) {
direction = -1;
elementToAnimate.style.backgroundColor = `hsl(${random}, 50%, 50%)`; // Color
change
} else if (position <= 0) {
direction = 1;
}
}, 10);
};

selectors.btn.addEventListener("click", () => startAnimation(selectors.box));

===============================================================================
<button id="rotate-btn">Start Rotation</button>
<div id="rotate-box" style="width: 100px; height: 100px; background-color:
lightpink; position: relative;"></div>
<script>
const selectors = {
btn: document.getElementById("rotate-btn"), // Fixed typo
box: document.getElementById("rotate-box")
};

const startAnimation = (elementToAnimate) => {


let angle = 0;
const intervalId = setInterval(() => {
angle += 1;
elementToAnimate.style.transform = `rotate(${angle}deg)`; // Corrected syntax
if (angle >= 360) {
angle = 0; // Reset the angle after a full rotation
}
}, 10);
};

selectors.btn.addEventListener("click", () => startAnimation(selectors.box)); //


Added '.btn'
</script>

===================================================================================
==========================
<button id="slide-btn">Start Slide</button>
<div id="slide-container" style="width: 400px; height: 100px; position: relative;
border: 2px solid black;">
<div id="slide-box" style="width: 50px; height: 50px; background-color:
lightblue; position: absolute; left: 0;"></div>
</div>
<script>
const selectors = {
btn: document.getElementById("slide-btn"),
container: document.getElementById("slide-container"),
box: document.getElementById("slide-box") // Corrected ID
};

const startAnimation = (elementToAnimate) => {


let position = 0;
let direction = 1;
const width = selectors.container.offsetWidth; // Corrected property

const intervalId = setInterval(() => {


position += direction; // Corrected syntax error
elementToAnimate.style.left = position + 'px';

// Change direction when the box reaches the edge of the container
if (position >= width - elementToAnimate.offsetWidth || position <= 0) {
direction *= -1; // Reverse direction
}
}, 10);
};

selectors.btn.addEventListener("click", () => startAnimation(selectors.box));


</script>

===================================================================================
=====================================
<button id="bounce-btn">Start Bounce</button>
<div id="bounce-container" style="width: 200px; height: 200px; position: relative;
border: 2px solid black; overflow: hidden;">
<div id="bounce-ball" style="width: 50px; height: 50px; background-color: orange;
border-radius: 50%; position: absolute; bottom: 0;"></div>
</div>
<script>
const selectors = {
btn: document.getElementById("bounce-btn"),
ball: document.getElementById("bounce-ball")
};

const startAnimation = (elementToAnimate) => {


let position = 0; // Start position
let direction = 1; // 1 for moving up, -1 for moving down
const intervalId = setInterval(() => {
position += direction;
elementToAnimate.style.bottom = position + 'px';

// Change direction when the ball hits the top or bottom of the container
if (position >= 150) { // Adjust based on the container size and ball size
direction = -1; // Start moving down
} else if (position <= 0) {
direction = 1; // Start moving up
}
}, 10);
};

selectors.btn.addEventListener("click", () => startAnimation(selectors.ball));


</script>

===================================================================================
===============================
<button id="slide-up-btn">Slide Up</button>
<div id="slide-box" style="width: 100px; height: 100px; background-color:
lightgreen; position: absolute; bottom: 0;"></div>

<script>
const selectors = {
btn: document.getElementById("slide-up-btn"),
box: document.getElementById("slide-box")
};

const startAnimation = (elementToAnimate) => {


let position = 0; // Start position at the bottom
const intervalId = setInterval(() => {
position += 1; // Move up by 1 pixel
elementToAnimate.style.bottom = position + 'px'; // Adjust the bottom
property
if (position >= 200) { // Stop when the box has moved up 200 pixels
clearInterval(intervalId);
}
}, 10); // Interval in milliseconds
};

selectors.btn.addEventListener("click", () => startAnimation(selectors.box)); //


Pass function reference
</script>

===================================================================================
========================
<button id="fade-in-btn">Fade In Box</button>
<div id="fade-box" style="width: 100px; height: 100px; background-color:
lightcoral; opacity: 0;"></div>

<script>
const selectors = {
btn: document.getElementById("fade-in-btn"),
box: document.getElementById("fade-box")
};

const startAnimation = (elementToStyle) => {


let opacity = 0;
const intervalId = setInterval(() => {
opacity += 0.1;
elementToStyle.style.opacity = opacity;
if (opacity >= 1) {
clearInterval(intervalId);
}
}, 100); // Increased the interval time for smoother fade-in
};

selectors.btn.addEventListener("click", () => startAnimation(selectors.box));


</script>

===================================================================================
================================
<button id="animate-btn">Start Animation</button>
<div id="box" style="width: 100px; height: 100px; background-color: lightblue;
position: absolute; left: 0;"></div>

<script>
const box = document.getElementById("box");
const btn = document.getElementById("animate-btn");

const startAnimation = (elementToStyle) => {


let position = 0;
const intervalId = setInterval(() => {
position += 1;
elementToStyle.style.left = position + 'px';

// Stop animation after moving 1000px


if (position >= 1000) {
clearInterval(intervalId);
}
}, 10); // Move every 10 milliseconds
};

btn.addEventListener("click", () => startAnimation(box));


</script>

===================================================================================
======
<!-- HTML -->
<div id="mouse-area" style="width: 100%; height: 300px; background-color:
lightblue;">
Hover over this area to see the mouse position.
</div>
<p id="mouse-position">Mouse position: </p>

<!-- JavaScript -->


<script>
function trackMousePosition() {
const mouseArea = document.getElementById("mouse-area");
const mousePosition = document.getElementById("mouse-position");

mouseArea.addEventListener("mousemove", (event) => {


const x = event.clientX - mouseArea.getBoundingClientRect().left;
const y = event.clientY - mouseArea.getBoundingClientRect().top;
mousePosition.textContent = `Mouse position: x=${x}, y=${y}`;
});
}
trackMousePosition();
</script>

===================================================================================
===========
<button id="single-click-btn">Single Click Me</button>
<button id="double-click-btn">Double Click Me</button>
<script>
const singleClickBtn = document.getElementById("single-click-btn");
const doubleClickBtn = document.getElementById("double-click-btn");

function handleSingleClick() {
singleClickBtn.addEventListener("click", () => {
alert("Single Click");
});
}

function handleDoubleClick() {
doubleClickBtn.addEventListener("dblclick", () => {
alert("Double Click");
});
}

handleSingleClick();
handleDoubleClick();
</script>

===================================================================================
=================
<form id="submit-form">
<label for="name">Enter your name:</label>
<input type="text" id="name-input" name="name">
<button type="submit">Submit</button>
</form>
<p id="message"></p>
<script>
function handleFormSubmition() {
const formToHandle = document.getElementById("submit-form");
const message = document.getElementById("message");

formToHandle.addEventListener("submit", (event) => {


event.preventDefault(); // Prevent the default form submission behavior
message.textContent = "Form submission prevented. Thank you!";
});
}

handleFormSubmition();
</script>

===================================================================================
<select id="color-select">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
<p id="color-paragraph">This text will change color based on your selection.</p>
<script>
function changeTextColor() {
const select = document.getElementById("color-select");
const paragraph = document.getElementById("color-paragraph");

select.addEventListener("change", () => {
if (select.value === "red") {
paragraph.style.color = "red";
} else if (select.value === "blue") {
paragraph.style.color = "blue";
} else if (select.value === "green") {
paragraph.style.color = "green";
} else {
paragraph.style.color = "black";
}
});
}

changeTextColor();
</script>

===================================================================================
=======
<input type="text" id="text-input" placeholder="Focus on me">
<p id="text-paragraph">Watch the text color change!</p>
<script>
function toggleTextColor()
{
const input = document.getElementById("text-input");
const paragraph = document.getElementById("text-paragraph");
input.addEventListener("focus", () => {
paragraph.style.color = "green";
});
input.addEventListener("blur", () => {
paragraph.style.color = "black";
});
}
toggleTextColor();
</script>

===================================================================================
===========
<button id="toggle-paragraph-btn">Hover Over Me</button>
<p id="paragraph" style="display: block;">This paragraph will be hidden on
hover.</p>
<script>
function toggleVisibility()
{
const btn = document.getElementById("toggle-paragraph-btn");
const paragraph = document.getElementById("paragraph");
btn.addEventListener("mouseover", () => {
paragraph.style.display = "none"; // Corrected property name
});
btn.addEventListener("mouseout", () => {
paragraph.style.display = "block"; // Corrected property name
});
}
toggleVisibility();
</script>
===================================================================================
=======================
<button id="color-btn">Double-Click Me</button>
<div id="color-box" style="width: 100px; height: 100px; background-color:
lightblue;"></div>
<script>
function changeBackgroundColor() {
const btn = document.getElementById("color-btn");
const box = document.getElementById("color-box");
btn.addEventListener("dblclick", () => {
box.style.backgroundColor = "yellow"; // Corrected property name
});
}
changeBackgroundColor();
</script>

===================================================================================
======
<button id="change-text-btn">Click Me</button>
<p id="text-paragraph">Original Text</p>
<script>
function changeText()
{
const btn = document.getElementById("change-text-btn");
const paragraph = document.getElementById("text-paragraph");
btn.addEventListener("click", () => {
paragraph.textContent = "Altered Text";
});
}
changeText();
</script>
===================================================================================
=========
<form id="checkbox-form">
<input type="checkbox" id="agree-checkbox">
<label for="agree-checkbox">I agree to the terms and conditions</label>
<br>
<button type="button" id="check-status-btn">Check Status</button>
</form>
<p id="checkbox-status"></p>

====== CSS ============


#checkbox-status {
color: green;
font-weight: bold;
}

======== JavaScript ===========


<script>
function handleCheckbox() {
const checkbox = document.getElementById("agree-checkbox");
const button = document.getElementById("check-status-btn");
const statusDisplay = document.getElementById("checkbox-status");

button.addEventListener("click", () => {
if (checkbox.checked) {
statusDisplay.innerHTML = "Checkbox is checked!";
} else {
statusDisplay.innerHTML = "Checkbox is unchecked!";
}
});
}

handleCheckbox();

</script>

==================================================================================
<form id="form-value">
<input type="text" id="text-input" placeholder="Enter text">
<button type="button" id="display-value-btn">Display Value</button>
</form>
<p id="value-display"></p>
<script>
function handleForm() {
const formToHandle = document.getElementById("form-value");
const button = document.getElementById("display-value-btn");
const input = document.getElementById("text-input");
const paragraph = document.getElementById("value-display");

button.addEventListener("click", () => {
paragraph.innerHTML = input.value;
});
}
handleForm();
</script>

===================================================================================
==============
<button id="toggle-bg-btn">Toggle Background Color</button>
<div id="box" style="width: 100px; height: 100px; background-color:
lightblue;"></div>
<script>
function toggleBackgroundColor()
{
const btn = document.getElementById("toggle-bg-btn");
const element = document.getElementById("box");
btn.addEventListener("click", () => {
if(element.style.backgroundColor === "lightgreen")
{
element.style.backgroundColor = "lightblue";
}
else
{
element.style.backgroundColor = "lightgreen";
}
});
}
toggleBackgroundColor();
</script>
===================================================================================
================
<button id="btn">Hover Me</button>
<p>lorem ipsum doors highlight color</p>

<script>
function changeColor() {
const paragraph = document.querySelector("p");
const btn = document.getElementById("btn");

btn.addEventListener("mouseover", () => {
paragraph.style.color = "red";
});

btn.addEventListener("mouseout", () => {
paragraph.style.color = ""; // Resets to the default color
});
}
changeColor();
</script>

===================================================================================
=======================
<button id="btn"> Hove Me </button>
<p> lorem ipsum doors highlight color </p>
<script>
function changeColor()
{
const paragraph = document.querySelector("p");
const btn = document.getElementById("btn");
btn.addEventListener("mouseover", () => {
paragraph.style.color = "red";
});
}
changeColor();
</script>
===================================================================================
===========

<button id="toggle-highlight-btn">Toggle Highlight on Double Click</button>


<p id="toggle-highlight-paragraph">Double-click on this paragraph to toggle
highlight.</p>

<!-- CSS -->


<style>
.highlight {
background-color: yellow;
}
</style>

<!-- JavaScript -->


<script>
function toggleClass() {
const paragraph = document.getElementById("toggle-highlight-paragraph");
paragraph.addEventListener("dblclick", () => {
paragraph.classList.toggle("highlight");
});
}
toggleClass();
</script>

===================================================================================
====
<button id="increase-font-btn">Increase Font Size</button>
<div id="text-container">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
</div>

<script>
function changeFontSize() {
const paragraphs = document.getElementById("text-
container").getElementsByTagName("p");
const button = document.getElementById("increase-font-btn");

button.addEventListener("click", () => {
for (let i = 0; i < paragraphs.length; i++) {
let currentSize = window.getComputedStyle(paragraphs[i],
null).getPropertyValue('font-size');
let newSize = parseFloat(currentSize) + 2 + "px";
paragraphs[i].style.fontSize = newSize;
}
});
}

changeFontSize();
</script>

===================================================================================
========================
<!-- HTML -->
<button id="count-btn">Count Paragraphs</button>
<div id="paragraph-container">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
</div>
<p id="paragraph-count">Paragraph count: </p>
<script>
function countParagraphs()
{
const button = document.getElementById("count-btn");
const container = document.getElementById("paragraph-container");
const result = document.getElementById("paragraph-count");
button.addEventListener("click", () => {
const count = container.getElementsByTagName("p").length;
result.innerHTML = "Paragraph count: " + count;
});
}
</script>

===================================================================================
=========================
<!-- HTML -->
<button id="change-text-btn">Change Text</button>
<p id="change-text">Original text.</p>
<script>
function changeText()
{
const button = document.getElementById("change-text-btn");
const paragraph = document.getElementById("change-text");
button.addEventListener("click", () => {
paragraph.innerHTML = "Text has been changed!";
})
}
changeText();
</script>

===================================================================================
=======================
<!-- HTML -->
<button id="toggle-btn">Toggle Highlight</button>
<p id="toggle-paragraph">This paragraph will be highlighted.</p>

<!-- CSS -->


<style>
.highlight {
background-color: yellow;
}
</style>
<script>
function toggleParagraph()
{
const paragraph = document.getElementById("toggle-paragraph");
const button = document.getElementById("toggle-btn");
button.addEventListener("click", () => {
paragraph.classList.toggle("highlight");
});
}
toggleParagraph();
</script>
===================================================================================
==================
<!-- HTML -->
<button id="replace-btn">Replace Paragraph</button>
<p id="replace-paragraph">This is the original content.</p>
<script>
function replaceParagraph() {
const paragraph = document.getElementById("replace-paragraph");
const button = document.getElementById("replace-btn");
button.addEventListener("click", () => {
paragraph.innerHTML = "this is the new text";
});
}
replaceParagraph();
</script>

===================================================================================
========================
<!-- HTML -->
<button id="remove-btn">Remove Last Paragraph</button>
<div id="container">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<!-- Paragraphs will be removed from here -->
</div>

<script>
function removeParagraph() {
const container = document.getElementById("container");
const button = document.getElementById("remove-btn");
button.addEventListener("click", () => {
if (container.lastElementChild) {
container.removeChild(container.lastElementChild);
}
});
}
removeParagraph();
</script>

===================================================================================
===================
<!-- HTML -->
<button id="add-btn">Add Paragraph</button>
<div id="container">
<!-- New paragraphs will be added here -->
</div>

<script>
function addParagraph() {
const container = document.getElementById("container");
const button = document.getElementById("add-btn");
button.addEventListener("click", () => {
const newParagraph = document.createElement("p");
newParagraph.textContent = "New paragraph added";
container.appendChild(newParagraph);
});
}
addParagraph();
</script>

===================================================================================
=
<script>
function toggleVisibility() {
const elements = document.getElementsByClassName("toggle-item");
const button = document.getElementById("toggle-btn");
button.addEventListener("click", () => {
for (let i = 0; i < elements.length; i++) {
if (elements[i].style.display === "none") {
elements[i].style.display = "block";
} else {
elements[i].style.display = "none";
}
}
});
}
toggleVisibility();
</script>

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

<script>
function changeBackgroundColor()
{
const elements = document.getElementsByClassName("hover-item");
for( let i = 0 ; i < elements.length ; i++)
{
elements[i].addEventListener("mouseover", () => {
elements[i].style.backgroundColor = "yellow";
})
}
}
changeBackgroundColor();
</script>

===================================================================================
===
<script>
function changeButtonText() {
const buttons = document.getElementsByClassName("btn");
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", () => {
buttons[i].textContent = "Clicked";
});
}
}
changeButtonText();
</script>

============================================================================
<script>
const items = document.getElementsByClassName("item");
for (let i = 0; i < items.length; i++) {
items[i].style.backgroundColor = "lightblue";
}
</script>

===================================================================================
=================
<script>
const header = document.getElementById("header");
header.innerHTML = "Welcome to My Website";
</script>

===================================================================================
=================
<!-- HTML -->
<button id="btn"> click me </button>
<div id="paragraphs">
<p> paragraph 1 </p>
<p> paragraph 2 </p>
<p> paragraph 3 </p>
</div>

<!-- CSS -->


.highlight {
background-color: yellow;
}
.italic {
font-style: italic;
}

<!-- JavaScript -->


<script>
function toggleClasses()
{
const paragraphs = document.querySelectorAll("p");
const button = document.getElementById("btn"); // Fixed the typo
button.addEventListener("click", () => {
for (let i = 0 ; i < paragraphs.length ; i++ )
{
paragraphs[i].classList.toggle("highlight");
paragraphs[i].classList.toggle("italic");
}
})
}
toggleClasses();
</script>

===================================================================================
===============================
<!-- HTML -->
<button id="btn"> click me </button>
<div id="paragraphs">
<p> paragraph 1 </p>
<p> paragraph 2 </p>
<p> paragraph 3 </p>
</div>

<!-- JavaScript -->


<script>
function addParagraph() {
document.getElementById("btn").addEventListener("click", () => {
const newParagraph = document.createElement("p"); // Corrected here
newParagraph.textContent = "New paragraph added";
document.getElementById("paragraphs").appendChild(newParagraph); // Corrected
here
});
}
addParagraph();
</script>

================================================================================
// HTML
<button id="btn"> click me </button>
<p> paragraph 1 </p>
<p> paragraph 2 </p>
<p> paragraph 3 </p>

// JavaScript
<script>
function changeText()
{
const elements = document.querySelectorAll("p");
document.getElementById("btn").addEventListener("click", () => {
for (let i = 0 ; i < elements.length ; i++)
{
elements[i].innerHTML = "this text has been changed";
}
})
}
changeText();
</script>
===================================================================================
========================
<button id="btn"> Click to Disable </button>

<script>
const button = document.getElementById("btn");
button.addEventListener("click", () => {
button.disabled = true; // Boolean, not a string
});
</script>

===================================================================================
=======================
// HTML
<button id="btn"> click me </button>
<p> paragraph 1 </p>
<p> paragraph 2 </p>
<p> paragraph 3 </p>

// stylesheet CSS
.highlight {
background-color: yellow;
}

//JavaScript
<script>
function changeBackgroundColor()
{
const paragraph = document.querySelectorAll("p");
document.getElementById("btn").addEventListener("click", () => {
for (let i = 0 ; i < paragraph.length ; i++)
{
paragraph[i].classList.toggle("highlight");
}
})
}
changeBackgroundColor();
</script>

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

<button id="btn"> click me </button>


<img src="./image1.png" alt="" />
<img src="./image2.png" alt="" />
<img src="./image3.png" alt="" />
<img src="./image4.png" alt="" />

<script>
function imageVisibility()
{
const elements = document.querySelectorAll("img");
document.getElementById("btn").addEventListener("click", () => {
for (let i = 0 ; i < elements.length ; i++)
{
if (elements[i].style.display === "none")
{
elements[i].style.display = "block";
}
else
{
elements[i].style.display = "none";
}
}
})
}
imageVisibility();
</script>

===================================================================================
========
<button id="btn"> click me </button>
<script>
function changeBackgroundColor() {
let index = 0;
document.getElementById("btn").addEventListener("click", () => {
index += 1;
if (index === 1) {
document.body.style.backgroundColor = "red";
} else if (index === 2) {
document.body.style.backgroundColor = "green";
} else if (index === 3) {
document.body.style.backgroundColor = "blue";
index = 0; // Reset the index after reaching the last color
}
});
}

changeBackgroundColor();
</script>

===================================================================================
=============
<button id="btn"> click me </button>
<img id="img" src="./image.png" alt="" />
<script>
function imageVisibility() {
const image = document.getElementById("img");
document.getElementById("btn").addEventListener("click", () => {
if (image.style.display === "none") {
image.style.display = "block";
} else {
image.style.display = "none";
}
});
}
imageVisibility();
</script>

===================================================================================
=====================
<button id="btn"> click me </button>
<img id="image" src="./image1.png" alt="" />
<script>
function changeImage()
{
const image = document.getElementById("image");
document.getElementById("btn").addEventListener("click", () => {
image.src="./iamge2.png";
})
}
changeImage();
</script>

===================================================================================
======================
<button id="btn">Click me</button>
<ul id="list">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ul>

<script>
function toggleListVisibility() {
const list = document.getElementById("list");
document.getElementById("btn").addEventListener("click", () => {
list.style.display = list.style.display === "none" ? "block" : "none";
});
}
toggleListVisibility();
</script>

===================================================================================
============
<button id="btn"> click me </button>
<ul>
<li> item 1 </li>
<li> item 2 </li>
<li> item 3 </li>
<li> item 4 </li>
</ul>

<script>
function listVisibility()
{
const list = document.querySelectorAll("li");
document.getElementById("btn").addEventListener("click", () => {
for (let i = 0 ; i < list.length ; i++)
{
if (list[i].style.display === "none")
{
list[i].style.display = "block";
}
else
{
list[i].style.display = "none";
}
}
});
}
listVisibility();
</script>
===================================================================================
=====================
// HTML
<button id="btn"> Click </button>
<p> pragraph 1 </p>
<p> pragraph 2 </p>
<p> pragraph 3 </p>

// stylesheet css
.paragraph {
color: red ;
}

//JavaScript
<script>
function changeColor()
{
const elements = document.querySelectorAll("p");
document.getElementById("btn").addEventListener("click", () => {
for (let i = 0 ; i < elements.length ; i++)
{
elements[i].classList.toggle("paragraph");
}
});
}
changeColor();
</script>
===================================================================================
============
<button id="btn"> click here </button>

<script>
function addClass() {
const elements = document.querySelectorAll("div");
document.getElementById("btn").addEventListener("click", () => {
for (let i = 0; i < elements.length; i++) {
elements[i].classList.add("highlight");
}
});
}

addClass(); // Call the function outside itself to initialize the functionality


</script>
```

Make sure you define the `highlight` class in your CSS for the background color
change. Example:

```css
.highlight {
background-color: yellow;
}
```

Now the script should work as expected! Let me know if you're ready for the next
task.
===================================================================================
=================
<button id="btn"> click </button>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<script>
function changeColor() {
const elements = document.querySelectorAll("p"); // Selector "p" should be in
quotes
document.getElementById("btn").addEventListener("click", () => {
for (let i = 0; i < elements.length; i++) {
elements[i].style.color = "red"; // Color value should be in quotes
}
});
}
changeColor();
</script>

===================================================================================
===================
<button id="btn"> click here </button>
<p id="pa"> sdfsdf </p>
<script>
function changeFontSize()
{
const paragraph = document.getElementById("pa");
document.getElementById("btn").addEventListener("click" , () => {
paragraph.style.fontSize = "16px";
});
}
changeFontSize();
</script>

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

<button id="btn">Change paragraph text</button>


<p id="paragraph">Text has not been changed yet. Click button to change.</p>

<script>
function changeText() {
const paragraph = document.getElementById("paragraph");
// Correct the 'btn' reference by using quotes
document.getElementById("btn").addEventListener("click", () => {
paragraph.innerHTML = "Text has been changed";
});
}

// Call the function to set up the event listener


changeText();
</script>

===================================================================================
======================
<button id="btn">Click to append item</button>
<ul id="list"></ul>
<script>
const list = document.getElementById("list");
document.getElementById("btn").addEventListener("click", () => {
// Create a new list item
const newItem = document.createElement("li");
// Set the text content of the new item
newItem.textContent = "New Item";
// Append the new item to the list
list.append(newItem);
});
</script>

===================================================================================
===========
<button id="btn">Click me</button>
<p id="paragraph">Text is not hidden. Click the button to hide.</p>

<script>
function handleClick() {
const paragraph = document.getElementById("paragraph");
document.getElementById("btn").addEventListener("click", () => {
if (paragraph.style.display === "none") {
paragraph.style.display = "block";
} else {
paragraph.style.display = "none";
}
});
}
handleClick();
</script>

===================================================================================
=============
<p id="btn"> hover me </p>
<script>
const paragraph = document.getElementById("btn");
paragraph.addEventListener("mouseover" , () => {
paragraph.style.color = "red";
});
paragraph.addEventListener("mouseout" , () => {
paragraph.style.color = "blue";
})
</script>
===================================================================================
=======================
<button id="btn">button not hovered</button>
<script>
const btn = document.getElementById("btn");

btn.addEventListener("mouseover", () => {
btn.textContent = "button hovered";
});

btn.addEventListener("mouseout", () => {
btn.textContent = "button not hovered";
});
</script>
===================================================================================
============================
<button id="btn">Click me</button>
<p id="paragraph">fdsjk</p>

<script>
function handleClick() {
const paragraph = document.getElementById("paragraph");
document.getElementById("btn").addEventListener("click", () => {
if (paragraph.style.display === "block") {
paragraph.style.display = "none";
} else {
paragraph.style.display = "block";
}
});
}

handleClick(); // Call the function to attach the event listener


</script>

===================================================================================
===================
<button id="btn"> click to change background color </button>
<script> document.getElementById("btn").addEventListener("click" , () => {
if (document.body.style.backgroundColor === "blue")
{
document.body.style.backgorundColor = "green";
}
else {
document.body.style.backgorundColor = "blue";
}
}) </script>
===================================================================================
====================
<button id="btn">Change Background</button>
<script>
document.getElementById("btn").addEventListener("click", () => {
document.body.style.backgroundColor = "red";
});
</script>

===================================================================================
=====
<button id="btn">Click Me!</button>
<script>
document.getElementById("btn").addEventListener('click', function() {
document.getElementById("btn").innerHTML = "Clicked!";
});
</script>

==============================================================================
document.queryselector('button').addEventListenner ('click', function(){
alert('Button Clicked');
})

==================================================================
function findLongestWord(S) {
if (S.length === 0) return ''; // Handle empty string case

let words = S.split(" ");


let longestWord = words[0];

for (let i = 1; i < words.length; i++) {


if (longestWord.length < words[i].length) {
longestWord = words[i];
}
}

return longestWord;
}

===================================================================================
=================
function removeDuplicates(S) {
let nonDuplicateArr = [];
for (let i = 0; i < S.length; i++) {
if (!nonDuplicateArr.includes(S[i])) {
nonDuplicateArr.push(S[i]);
}
}
return nonDuplicateArr.join(""); // Convert array back to string
}

===================================================================================
====================
function reverseString (S)
{
let reverseString = "";
for (let i = S.length - 1 ; i >= 0 ; i-- )
{
reverseString += S[i] ;
}
return reverseString ;
}

function isPalindrome (S)


{
S1 = S.toLowerCase();
return reverseString(S1) === S1 ;
}

===================================================================================
======================
function capitalizeWords (S)
{
words = S.split(" ");
for (let i = 0 ; i < words.length ; i++ )
{
if (words[i][0] === words[i][0].toLowerCase())
{
words[i] = words[i][0].toUpperCase() + words[i].slice(1);
}
}
return words.join(" ");
}
===================================================================================
======================
function reverseString (S)
{
let reverseString = "";
for (let i = S.length - 1 ; i >= 0 ; i-- )
{
reverseString += S[i] ;
}
return reverseString ;
}

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

function updateItemPrice(cart, itemName, newPrice) {


const existingItem = cart.find(cartItem => cartItem.name === itemName);
if (existingItem)
{
existingItem.price = newPrice ;
return cart;
}
else
return "Item not found";

===================================================================================
=================
function calculatePrice(cart) {
let totalPrice = 0;
for (let i = 0; i < cart.length; i++) {
totalPrice += cart[i].price;
}
return totalPrice;
}

function calculateAveragePrice(cart) {
if (cart.length === 0) return 0; // Handle edge case where cart is empty
return calculatePrice(cart) / cart.length;
}

===================================================================================
======
function calculateDiscountedPrice(price, discountPercentage, quantity) {

let discountMultiplier = (100 - discountPercentage) / 100;


let discountedPrice = price * discountMultiplier;
return discountedPrice * quantity;
}

===============================================================================
findItemBelowPrice (cart , maxPrice)
{
let itemsBelowPrice = [] ;
for (let i = 0 ; i < cart.length ; i++ )
{
if (cart[i].price < maxPrice)
{
itemsBelowPrice.push(cart[i]);
}
}
return itemsBelowPrice ;
}

===================================================================================
=====================
function findHighestPricedItem(cart) {
if (cart.length === 0) {
return null; // Handle the case where the cart is empty
}

let highestPricedItem = cart[0]; // Initialize with the first item

for (let i = 1; i < cart.length; i++) {


if (cart[i].price > highestPricedItem.price) {
highestPricedItem = cart[i]; // Update the item with the highest price
}
}

return highestPricedItem; // Return the entire item object


}

===================================================================================
==================
function groupItemsByCategory(cart) {
// Create an empty object to hold the grouped items
const groupedItems = {};

// Iterate over each item in the cart


for (const item of cart) {
// Check if the category already exists in the groupedItems object
if (!groupedItems[item.category]) {
// If not, initialize it with an empty array
groupedItems[item.category] = [];
}

// Add the current item to the appropriate category array


groupedItems[item.category].push(item);
}

return groupedItems;
}

// Example usage:
const cart = [
{ name: 'Item A', category: 'Electronics', price: 30 },
{ name: 'Item B', category: 'Clothing', price: 20 },
{ name: 'Item C', category: 'Electronics', price: 50 },
{ name: 'Item D', category: 'Clothing', price: 40 }
];

console.log(groupItemsByCategory(cart));

============================================
function sortCartByPrice(cart) {
// Sort cart array by price in ascending order
cart.sort((a, b) => a.price - b.price);
return cart;
}

===================================================================================
===================
function checkRange(price, minPrice, maxPrice) {
return (price >= minPrice && price <= maxPrice);
}

function filterItemsByPriceRange(cart, minPrice, maxPrice) {


let filteredItems = [];
for (let i = 0; i < cart.length; i++) {
if (checkRange(cart[i].price, minPrice, maxPrice)) {
filteredItems.push(cart[i]);
}
}
return filteredItems;
}

===================================================================================
==================
function findItemByName(cart, item) {
for (let i = 0; i < cart.length; i++) {
if (cart[i].name === item) {
return cart[i];
}
}
return null; // Return null if the item is not found
}

===================================================================================
====================
function getTotalPrice(cart) {
let totalPrice = 0;
for (let i = 0; i < cart.length; i++) {
totalPrice += cart[i].price * cart[i].quantity;
}
return totalPrice;
}

===================================================================================
=====
function getTotalItems(cart) {
let totalItems = 0;
for (let i = 0; i < cart.length; i++) {
totalItems += cart[i].quantity; // Summing up quantities
}
return totalItems;
}

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

function updateCartQuantity(cart, item, quantity) {


const existingItem = cart.find(cartItem => cartItem.name === item);
if (existingItem) {
existingItem.quantity = quantity; // Update to the new quantity
return cart;
} else {
return "This item doesn't exist";
}
}

===================================================================================
============
function removeItemFromCart(cart, item) {
const index = cart.findIndex(cartItem => cartItem.name === item);
if (index !== -1) {
cart.splice(index, 1); // Remove the item at the found index
return cart;
} else {
return "There's no item with that name.";
}
}

In the `splice()` method, the `1` represents the number of elements to remove from
the array starting at the specified index.

Here's how `splice()` works:


```javascript
array.splice(startIndex, deleteCount);
```

- `startIndex`: The index from where to start removing elements.


- `deleteCount`: The number of elements to remove, starting from `startIndex`.

So, in the code:

```javascript
cart.splice(index, 1);
```

- `index` is the position of the item to remove (found using `findIndex`).


- `1` means remove **one item** at that position.

If you wanted to remove more than one item (e.g., consecutive items), you could
increase the `1` to whatever number of items you'd like to remove.

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

function addItemToCart(cart, item, quantity) {


// Check if the item already exists in the cart
const existingItem = cart.find(cartItem => cartItem.name === item);

if (existingItem) {
// If the item exists, increase its quantity
existingItem.quantity += quantity;
} else {
// If the item doesn't exist, add it to the cart
cart.push({ name: item, quantity: quantity });
}
return cart;
}

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

// Check if the string is empty or contains only whitespace


function isEmpty(str) {
return str.trim().length === 0;
}

// Check if the name contains only letters and is not empty


function isValidName(name) {
// Ensure name is not empty and only contains letters (uppercase or lowercase)
const lettersOnly = /^[A-Za-z]+$/;
return !isEmpty(name) && lettersOnly.test(name);
}

// Check if the email is valid


function isValidEmail(email) {
// Simple email validation
let atSymbolIndex = email.indexOf('@');
if (atSymbolIndex === -1 || email.indexOf('@', atSymbolIndex + 1) !== -1) {
return false;
}

let localPart = email.substring(0, atSymbolIndex);


let domainPart = email.substring(atSymbolIndex + 1);

if (localPart.length === 0 || domainPart.length === 0) {


return false;
}

let dotIndex = domainPart.lastIndexOf('.');


if (dotIndex === -1 || dotIndex === domainPart.length - 1) {
return false;
}

let domainExtension = domainPart.substring(dotIndex + 1);


return domainExtension.length >= 2;
}

// Check if the message is at least 10 characters long


function isValidMessage(message) {
return message.length >= 10;
}

function validateContactForm(name, email, message) {


if (!isValidName(name)) {
return "Name should contain only letters and should not be empty.";
}
if (!isValidEmail(email)) {
return "Invalid email format.";
}
if (!isValidMessage(message)) {
return "Message should be at least 10 characters long.";
}
return true; // All validations passed
}

===================================================================================
==
function filterItemsByCategory(arr, category) {
let categoryArr = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i].category === category) {
categoryArr.push(arr[i]);
}
}
return categoryArr;
}

===================================================================================
// Function to add a new item to the todo list
function addTodoItem(todoList, item) {
todoList.push(item);
}

// Function to remove an item from the todo list by matching the text
function removeTodoItem(todoList, itemText) {
const index = todoList.findIndex(todo => todo.text === itemText);
if (index !== -1) {
todoList.splice(index, 1); // Remove the item if found
}
}

// Function to mark a todo item as completed


function markAsComplete(todoList, itemText) {
const todo = todoList.find(todo => todo.text === itemText);
if (todo) {
todo.completed = true; // Set the completed property to true
}
}

// Function to get the current todo list


function getTodoList(todoList) {
return todoList;
}

// Example usage
let todoList = [];

// Add todo items


addTodoItem(todoList, { text: "Buy milk", completed: false });
addTodoItem(todoList, { text: "Walk the dog", completed: false });

console.log(getTodoList(todoList));
// Output: [{ text: "Buy milk", completed: false }, { text: "Walk the dog",
completed: false }]

// Mark "Buy milk" as complete


markAsComplete(todoList, "Buy milk");

console.log(getTodoList(todoList));
// Output: [{ text: "Buy milk", completed: true }, { text: "Walk the dog",
completed: false }]

// Remove "Walk the dog" from the todo list


removeTodoItem(todoList, "Walk the dog");

console.log(getTodoList(todoList));
// Output: [{ text: "Buy milk", completed: true }]

=================================================================================
function calculateOccurrence(arr, number) {
let numberOccurrence = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === number) {
numberOccurrence += 1;
}
}
return numberOccurrence;
}

function findMostFrequentElement(arr) {
let frequencyMap = new Map();

// Count the frequency of each element


for (let i = 0; i < arr.length; i++) {
let element = arr[i];
if (frequencyMap.has(element)) {
frequencyMap.set(element, frequencyMap.get(element) + 1);
} else {
frequencyMap.set(element, 1);
}
}

// Find the element with the highest frequency


let mostFrequentElement = null;
let maxFrequency = 0;

for (let [element, frequency] of frequencyMap.entries()) {


if (frequency > maxFrequency) {
maxFrequency = frequency;
mostFrequentElement = element;
}
}

return mostFrequentElement;
}

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

function calculateItemPrice(item) {
return item.price * item.quantity;
}

function calculateTotalPrice(cart) {
let totalPrice = 0;
for (let i = 0; i < cart.length; i++) {
totalPrice += calculateItemPrice(cart[i]);
}
return totalPrice;
}

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

function isOdd(number) {
return number % 2 !== 0; // Return true for odd numbers
}

function filterEvenNumbers(arr) {
let oddArr = [];
for (let i = 0; i < arr.length; i++) {
if (isOdd(arr[i])) {
oddArr.push(arr[i]);
}
}
return oddArr;
}

===================================================================================
==
function generateRandomNumber(min, max) {
let randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
return randomNumber;
}

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

function isValidURL(URL) {
// Check if the URL starts with http:// or https://
if (URL.startsWith("http://") || URL.startsWith("https://")) {
// Extract the part after the protocol
const domainAndPath = URL.split("://")[1];

// Check if the domain exists (i.e., there's something after http:// or


https://)
if (domainAndPath.length > 0) {
return true;
}
}
return false;
}

===================================================================================
=========
function isValidEmail(email) {
// Check if the email contains exactly one '@'
let atSymbolIndex = email.indexOf('@');
if (atSymbolIndex === -1 || email.indexOf('@', atSymbolIndex + 1) !== -1) {
return false;
}

// Split the email into local part and domain part


let localPart = email.substring(0, atSymbolIndex);
let domainPart = email.substring(atSymbolIndex + 1);
// Check if both local and domain parts are non-empty
if (localPart.length === 0 || domainPart.length === 0) {
return false;
}

// Check if the domain part contains a '.'


let dotIndex = domainPart.lastIndexOf('.');
if (dotIndex === -1 || dotIndex === domainPart.length - 1) {
return false;
}

// Ensure that the domain extension (after the last dot) has at least 2
characters
let domainExtension = domainPart.substring(dotIndex + 1);
if (domainExtension.length < 2) {
return false;
}

return true;
}

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

function checkCharactersLength(password) {
return password.length >= 8;
}

function checkLower(password) {
for (let i = 0; i < password.length; i++) {
if (password[i] === password[i].toLowerCase() && isNaN(password[i])) {
return true;
}
}
return false;
}

function checkUpper(password) {
for (let i = 0; i < password.length; i++) {
if (password[i] === password[i].toUpperCase() && isNaN(password[i])) {
return true;
}
}
return false;
}

function checkDigit(password) {
for (let i = 0; i < password.length; i++) {
if (!isNaN(password[i])) {
return true;
}
}
return false;
}

function checkSpecialChar(password) {
const specialChars = "!@#$%^&*";
for (let i = 0; i < password.length; i++) {
if (specialChars.includes(password[i])) {
return true;
}
}
return false;
}

function isStrongPassword(password) {
return (
checkCharactersLength(password) &&
checkLower(password) &&
checkUpper(password) &&
checkDigit(password) &&
checkSpecialChar(password)
);
}

// Test cases
console.log(isStrongPassword("Password123!")); // true
console.log(isStrongPassword("weakpass")); // false

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

function isPangram(str) {
// Convert the string to lowercase to handle case insensitivity
let lowerCaseStr = str.toLowerCase();

// Create a set to store unique letters


let letterSet = new Set();

// Loop through each character in the string


for (let i = 0; i < lowerCaseStr.length; i++) {
let char = lowerCaseStr[i];

// Only add alphabetic characters to the set


if (char >= 'a' && char <= 'z') {
letterSet.add(char);
}
}

// If the set contains 26 unique letters, it's a pangram


return letterSet.size === 26;
}

// Example usage
console.log(isPangram("The quick brown fox jumps over the lazy dog")); // true
console.log(isPangram("Hello World")); // false

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

function findMissingNumber(arr) {
let n = arr.length + 1; // There should be n numbers, but one is missing
let totalSum = (n * (n + 1)) / 2; // Sum of all numbers from 1 to n
let arrSum = 0;
for (let i = 0; i < arr.length; i++) {
arrSum += arr[i]; // Sum of elements in the array
}

return totalSum - arrSum; // The difference is the missing number


}

===================================================================================
====================
function fibonacci(n) {
if (n === 0) {
return 0; // Base case for 0
}
if (n === 1) {
return 1; // Base case for 1
}
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}

===================================================================================
========
function sumDigits(number) {
let sumDigits = 0;

while (number > 0) {


let restDivision = number % 10;
sumDigits += restDivision;
number = Math.floor(number / 10); // Corrected division
}

return sumDigits;
}

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

function isAnagram(S1, S2) {


if (S1.length !== S2.length) {
return false;
}

let sortedS1 = S1.split('').sort().join('');


let sortedS2 = S2.split('').sort().join('');

return sortedS1 === sortedS2;


}

================================================================================
function flattenArray (arr)
{
return arr.flat(Infinity);
}

===============================================================================
function removesDuplicates (arr)
{
let uniqueArr = [];
for (let i = 0 ; i < arr.length ; i++)
{
if (!uniqueArr.includes(arr[i]))
{
unique.Arr.push(arr[i]);
}
}
return uniqueArr ;
}

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

functtion reverseWord (word)


{
let reverseWord = "";
for ( let i = word.length-1 ; i >= 0 ; i-- )
{
reverseWord += word[i];
}
return reverseWord ;
}

function reverseWords (S)


{
let words = S.split(" ");
for ( let i = 0 ; i < words.length ; i++)
{
words[i] = reverseWord(words[i]);
}
return words.join(" ");
}

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

function isVowel (number)


{
const vowels = ['a','o','e','i','u'];
for (let i = 0 ; i < vowels.length ; i++)
{
if (number === vowels[i])
{ return true ;}
}
}

function countVowels (word)


{
let countVowels = 0 ;
for (let i = 0 ; i < word.length ; i++)
{
if(isVowel(word[i]))
{
countVowels++ ;
}
}
return countVowels ;
}
==========================================================

function multiplyArray (arr)


{
let multiplyArr = 1 ;
for ( let i = 0 ; i < arr.length ; i++ )
{
multiplyArr *= arr[i];
}
return multiplyArr ;
}

function isPositive (number)


{
if (number > 0)
{
return true ;
}
else return false ;
}

function addNumbers (number1, number2) {


return number1 + number2;
}

You might also like