0% found this document useful (0 votes)
15 views72 pages

QB - CSS PR Exam 2024 P16

The document contains a series of JavaScript programming tasks, including creating an employee object, a simple calculator, and various functions for calculating factorials, generating Fibonacci series, and handling user input. Each task includes HTML structure and JavaScript code snippets to demonstrate the required functionality. The tasks are designed to test various JavaScript concepts such as objects, functions, arrays, and user interaction through prompts and alerts.

Uploaded by

aksp006
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)
15 views72 pages

QB - CSS PR Exam 2024 P16

The document contains a series of JavaScript programming tasks, including creating an employee object, a simple calculator, and various functions for calculating factorials, generating Fibonacci series, and handling user input. Each task includes HTML structure and JavaScript code snippets to demonstrate the required functionality. The tasks are designed to test various JavaScript concepts such as objects, functions, arrays, and user interaction through prompts and alerts.

Uploaded by

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

Prepare all questions,i will be assigning 2 questions to each of

you at a random on the day of practical exam.


Sr. Question
No.
Write a Java Script Program to create an Object Employee with it s
1 attributes as emp_name, emp_age, salary, dept and use getter and setter
properties on it.

<!DOCTYPE html>
<html>
<body>
<h1>Employee Details</h1>

<label>Name: </label>
<input type="text" id="name" placeholder="Enter Name"><br><br>

<label>Age: </label>
<input type="number" id="age" placeholder="Enter Age"><br><br>

<label>Salary: </label>
<input type="number" id="salary" placeholder="Enter
Salary"><br><br>

<label>Department: </label>
<input type="text" id="dept" placeholder="Enter
Department"><br><br>

<button onclick="showEmployee()">Submit</button>

<h2>Employee Details:</h2>
<p id="output"></p>

<script>
const employee = {
emp_name: "",
emp_age: 0,
salary: 0,
dept: "",

get name() { return this.emp_name; },


get age() { return this.emp_age; },
get employeeSalary() { return this.salary; },
get department() { return this.dept; },
set name(value) { this.emp_name = value; },
set age(value) { this.emp_age = value; },
set employeeSalary(value) { this.salary = value; },
set department(value) { this.dept = value; }
};

function showEmployee() {
employee.name = document.getElementById("name").value;
employee.age = document.getElementById("age").value;
employee.employeeSalary =
document.getElementById("salary").value;
employee.department = document.getElementById("dept").value;

document.getElementById("output").innerHTML = `
Name: ${employee.name}<br>
Age: ${employee.age}<br>
Salary: ${employee.employeeSalary}<br>
Department: ${employee.department}`;
}
</script>
</body>
</html>

Write a JS Program to create a simple calculator. The calculator should


2 have the following functionalities: addition, subtraction, multiplication and
division of 2 numbers, and square and cube of a single number. Achive it
using switch case.

<!DOCTYPE html>
<html>
<body>
<h1>Simple Calculator</h1>
<label for="operation">Choose Operation:</label>
<select id="operation">
<option value="add">Add</option>
<option value="subtract">Subtract</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
<option value="square">Square</option>
<option value="cube">Cube</option>
</select>
<br>
<input type="number" id="num1" placeholder="Enter first number">
<br>
<input type="number" id="num2" placeholder="Enter second number (if
needed)">
<br>
<button onclick="calculate()">Calculate</button>
<h2 id="result">Result: </h2>

<script>
function calculate() {
const operation = document.getElementById("operation").value;
const num1 = parseFloat(document.getElementById("num1").value);
const num2 = parseFloat(document.getElementById("num2").value);
let result;

switch (operation) {
case "add":
result = num1 + num2;
break;
case "subtract":
result = num1 - num2;
break;
case "multiply":
result = num1 * num2;
break;
case "divide":
if (num2 !== 0) {
result = num1 / num2;
} else {
result = "Division by zero is not allowed!";
}
break;
case "square":
result = num1 ** 2;
break;
case "cube":
result = num1 ** 3;
break;
default:
result = "Invalid operation!";
}

document.getElementById("result").innerText = `Result: ${result}`;


}
</script>
</body>
</html>

3 Write a Java Script to Display a Factorail of a Number using for Loop.


Result should be poped out after user enters the number.
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Factorial Calculator</h1>
<input type="number" id="number" placeholder="Enter a number"
min="0">
<br>
<button onclick="calculateFactorial()">Calculate Factorial</button>
<script>
function calculateFactorial() {
const num = parseInt(document.getElementById("number").value);
if (isNaN(num) || num < 0) {
alert("Please enter a valid non-negative number!");
return;
}
let factorial = 1;
for (let i = 1; i <= num; i++) {
factorial *= i;
}
alert(`The factorial of ${num} is: ${factorial}`);
}
</script>
</body>
</html>

4 Write a Java Script to Display Fibonacci Series according to the limit


entered by the user.
<!DOCTYPE html>
<html>
<body>
<h1>Fibonacci Series Generator</h1>
<input type="number" id="limit" placeholder="Enter the limit"
min="1">
<br>
<button onclick="generateFibonacci()">Generate Series</button>
<script>
function generateFibonacci() {
const limit = parseInt(document.getElementById("limit").value);
if (isNaN(limit) || limit <= 0) {
alert("Please enter a valid positive number!");
return;
}
let fibSeries = [];
let a = 0, b = 1;
while (a <= limit) {
fibSeries.push(a);
let next = a + b;
a = b;
b = next;
}
alert(`Fibonacci series up to ${limit}: ${fibSeries.join(", ")}`);
}
</script>
</body>
</html>

5 Write a program to use window object methods such as alert, prompt and
confirm.
<!DOCTYPE html>
<html>
<body>
<h1>Window Object Methods Example</h1>
<button onclick="useWindowMethods()">Click Me</button>
<script>
function useWindowMethods() {
alert("Welcome to the Window Object Methods Demo!");
const name = prompt("What is your name?");
if (name) {
if (confirm(`Your name is ${name}. Is that correct?`)) {
alert(`Nice to meet you, ${name}!`);
} else {
alert("Please try again!");
}
} else {
alert("You didn't enter your name!");
}
}
</script>
</body>
</html>

Write a Java Script to create an Array by taking elements of it from the


6 user. Then arrange the Array in Assending and Descending order in a
Tabular Format.

<!DOCTYPE html>
<html lang="en">
<body>
<h1>Array Sorting</h1>
<button onclick="createArray()">Enter Array Elements</button>
<div id="table-container"></div>

<script>
function createArray() {
const input = prompt("Enter numbers separated by commas:");

if (!input) {
alert("No input provided!");
return;
}

const arr = input.split(",").map(Number);

if (arr.some(isNaN)) {
alert("Please enter valid numbers!");
return;
}

const ascending = [...arr].sort((a, b) => a - b);


const descending = [...arr].sort((a, b) => b - a);

document.getElementById("table-container").innerHTML = `
<table border="1" style="margin-top: 20px;
border-collapse: collapse; width: 50%; text-align: center;">
<tr><th>Original</th>
<th>Ascending</th>
<th>Descending</th></tr>
<tr>
<td>${arr.join(", ")}</td>
<td>${ascending.join(", ")}</td>
<td>${descending.join(", ")}</td>
</tr>
</table>`;
}

</script>

</body>
</html>

7 Write a Java Script to Demonstrate the use of Functions used with array.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function arrayFunctions() {
let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(num => num * num);
document.getElementById("squares").innerHTML = "Squared
Numbers: " + squares.join(", ");
let evenNumbers = numbers.filter(num => num % 2 === 0);
document.getElementById("evenNumbers").innerHTML = "Even
Numbers: " + evenNumbers.join(", ");
let sum = numbers.reduce((total, num) => total + num, 0);
document.getElementById("sum").innerHTML = "Sum of
Numbers: " + sum;
}
</script>
</head>
<body>
<h1>Array Functions Example</h1>
<button onclick="arrayFunctions()">Click to Run Functions</button>
<p id="squares"></p>
<p id="evenNumbers"></p>
<p id="sum"></p>
</body>
</html>

Write a Java Script to take name and age from user and pass it as an
8 argument to a function and display that the user is eligible for voting or
not.

<!DOCTYPE html>
<html lang="en">
<head>
<script>
function checkEligibility(name, age) {
if (age >= 18) {
document.getElementById("result").innerText = name + " is
eligible to vote.";
} else {
document.getElementById("result").innerText = name + " is
not eligible to vote.";
}
}
function getUserInput() {
let name = document.getElementById("name").value;
let age = document.getElementById("age").value;
age = parseInt(age);
checkEligibility(name, age);
}
</script>
</head>
<body>
<h1>Check Voting Eligibility</h1>
<label for="name">Enter your Name:</label>
<input type="text" id="name" required><br><br>

<label for="age">Enter your Age:</label>


<input type="number" id="age" required><br><br>

<button onclick="getUserInput()">Check Eligibility</button>

<p id="result"></p>
</body>
</html>

9 Develop a Javascript to convert the given character to unicode and


vice-versa.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function charToUnicode() {
let char = document.getElementById("charInput").value;
if (char) {
let unicodeValue = char.charCodeAt(0);
document.getElementById("unicodeResult").innerText =
"Unicode of '" + char + "' is: " + unicodeValue;
} else {
document.getElementById("unicodeResult").innerText = "Please
enter a character.";
}
}
function unicodeToChar() {
let unicode = document.getElementById("unicodeInput").value;
if (unicode) {
let charValue = String.fromCharCode(unicode);
document.getElementById("charResult").innerText = "Character
for Unicode " + unicode + " is: '" + charValue + "'";
} else {
document.getElementById("charResult").innerText = "Please
enter a Unicode value.";
}
}
</script>
</head>
<body>
<h1>Convert Character to Unicode and Unicode to Character</h1>
<!-- Character to Unicode Conversion -->
<h2>Character to Unicode</h2>
<label for="charInput">Enter a Character:</label>
<input type="text" id="charInput" maxlength="1" required>
<button onclick="charToUnicode()">Convert to Unicode</button>
<p id="unicodeResult"></p>
<!-- Unicode to Character Conversion -->
<h2>Unicode to Character</h2>
<label for="unicodeInput">Enter Unicode:</label>
<input type="number" id="unicodeInput" required>
<button onclick="unicodeToChar()">Convert to Character</button>
<p id="charResult"></p>
</body>
</html>

Write a JavaScript program that will display list of student (atleast 5


10 students)in ascending order according to the marks & calculate the
average performance of the class.

<!DOCTYPE html>
<html lang="en">
<head>
<script>
const students = [
{ name: "Alice", marks: 75 },
{ name: "Bob", marks: 85 },
{ name: "Charlie", marks: 90 },
{ name: "David", marks: 60 },
{ name: "Eva", marks: 80 }
];
function sortStudentsByMarks() {
students.sort((a, b) => a.marks - b.marks);
displayStudents();
}
function displayStudents() {
let studentList = "";
let totalMarks = 0;
students.forEach(student => {
studentList += `${student.name}: ${student.marks}<br>`;
totalMarks += student.marks;
});
let averageMarks = totalMarks / students.length;
document.getElementById("studentList").innerHTML =
studentList;
document.getElementById("averageMarks").innerHTML =
"Average Marks: " + averageMarks.toFixed(2);
}
window.onload = sortStudentsByMarks;
</script>
</head>
<body>
<h1>Student Marks List</h1>
<button onclick="sortStudentsByMarks()">Sort by Marks</button>
<div>
<h2>Sorted Student List:</h2>
<p id="studentList"></p>
<p id="averageMarks"></p>
</div>
</body>
</html>

11 Write a Java Script to demonstrate all the types of Functions.


<!DOCTYPE html>
<html>
<head>
<script>
function regularFunction() {
return "This is a Regular Function.";
}
const anonymousFunction = function() {
return "This is an Anonymous Function.";
};
const arrowFunction = () => {
return "This is an Arrow Function.";
};
(function() {
alert("This is an IIFE (Immediately Invoked Function
Expression).");
})();
const functionExpression = function greeting(name) {
return "Hello, " + name + "!";
};
function performAction(callback) {
const result = callback();
alert("Callback function result: " + result);
}
function demonstrateFunctions() {
document.getElementById("regular").innerText =
regularFunction();
document.getElementById("anonymous").innerText =
anonymousFunction();
document.getElementById("arrow").innerText = arrowFunction();
document.getElementById("functionExpression").innerText =
functionExpression("Alice");
performAction(() => "This is the result from the callback
function.");
}
</script>
</head>
<body onload="demonstrateFunctions()">
<h1>Demonstrating Different Types of Functions in JavaScript</h1>
<h2>1. Regular Function</h2>
<p id="regular"></p>
<h2>2. Anonymous Function</h2>
<p id="anonymous"></p>
<h2>3. Arrow Function</h2>
<p id="arrow"></p>
<h2>4. Function Expression</h2>
<p id="functionExpression"></p>
</body>
</html>

Write a Java Script to take String from the user. Then take the start and
12 end point for substring from the user and display the result in alert box.(
eg. hello world is entered and user gives 6 and 10 then world must be
displayed).

<!DOCTYPE html>
<html lang="en">
<head>
<script>
function getSubstring() {
let inputString = prompt("Enter a string:");
let startPoint = parseInt(prompt("Enter the start index for
substring:"));
let endPoint = parseInt(prompt("Enter the end index for
substring:"));
let substring = inputString.slice(startPoint, endPoint);
alert("The extracted substring is: " + substring);
}
</script>
</head>
<body>
<h1>Substring Extraction</h1>
<button onclick="getSubstring()">Get Substring</button>
</body>
</html>

Write a Program to take input a String from user and demonstrate the
13 difference between the split(), substring() and substr() methods of String.

<!DOCTYPE html>
<html lang="en">
<head>
<script>
function demonstrateStringMethods() {
let inputString = prompt("Enter a string:");
let splitResult = inputString.split(" ");
let splitOutput = "Result of split() method: " + splitResult.join(", ");

let substringResult = inputString.substring(2, 6);


let substringOutput = "Result of substring() method: " +
substringResult;

let substrResult = inputString.substr(2, 4);


let substrOutput = "Result of substr() method: " + substrResult;

alert(splitOutput);
alert(substringOutput);
alert(substrOutput);
}
</script>
</head>
<body>
<h1>Demonstrating String Methods: split(), substring(), and
substr()</h1>
<button onclick="demonstrateStringMethods()">Demonstrate String
Methods</button>
</body>
</html>

Write a Java Script to create an Associative array of Fruits with its price (
14 "Fruit" : price) by taking input from the user and display only those fruits
whose price is greater than 500 in a tabular form.

<!DOCTYPE html>
<html lang="en">
<head>
<script>
function filterFruitsByPrice() {
let fruits = {};

let numFruits = parseInt(prompt("How many fruits do you want to


enter?"));

for (let i = 0; i < numFruits; i++) {


let fruitName = prompt("Enter fruit name " + (i + 1) + ":");
let fruitPrice = parseFloat(prompt("Enter the price of " +
fruitName + ":"));
fruits[fruitName] = fruitPrice; // Associating fruit with its price
}
let table = "<table
border='1'><tr><th>Fruit</th><th>Price</th></tr>";

for (let fruit in fruits) {


if (fruits[fruit] > 500) {
table += "<tr><td>" + fruit + "</td><td>" + fruits[fruit] +
"</td></tr>";
}
}

table += "</table>";

document.getElementById("result").innerHTML = table;
}
</script>
</head>
<body>
<h1>Filter Fruits by Price</h1>
<button onclick="filterFruitsByPrice()">Enter Fruit Prices</button>
<div id="result"></div>
</body>
</html>

15 Write a Java Script to demonstrate various String functions(minimum 8


functions).
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function demonstrateStringFunctions() {
let str = " Hello, JavaScript World! ";
let results = `
<h3>Original String:</h3> "${str}" <br><br>
<h3>toUpperCase:</h3> "${str.toUpperCase()}" <br><br>
<h3>toLowerCase:</h3> "${str.toLowerCase()}" <br><br>
<h3>trim:</h3> "${str.trim()}" <br><br>
<h3>charAt(7):</h3> "${str.charAt(7)}" <br><br>
<h3>indexOf('JavaScript'):</h3> ${str.indexOf("JavaScript")}
<br><br>
<h3>substring(7, 18):</h3> "${str.substring(7, 18)}" <br><br>
<h3>split(', '):</h3> [${str.split(" ").join(" | ")}] <br><br>
<h3>replace('JavaScript', 'HTML'):</h3>
"${str.replace("JavaScript", "HTML")}" <br><br>
`;
document.getElementById("output").innerHTML = results;
}
</script>
</head>
<body onload="demonstrateStringFunctions()">
<h1>String Functions in JavaScript</h1>
<div id="output"></div>
</body>
</html>

Write a JavaScript program for a travel booking form that collects details
16 like Traveler Name, Destination, Travel Date, and Number of Travelers.
Use a drop-down menu to allow users to select the mode of transport
(e.g., Air, Train, Bus). Depending on the selected transport mode,
dynamically update a list of available companies for booking.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function updateCompanies() {
const transportMode =
document.getElementById("transportMode").value;
const companiesDropdown =
document.getElementById("companyList");

const companies = {
"Air": ["Air India", "IndiGo", "SpiceJet", "Vistara"],
"Train": ["Indian Railways", "Shatabdi Express", "Rajdhani
Express"],
"Bus": ["VRL", "SRS Travels", "KSRTC"]
};

if (companies[transportMode]) {
companiesDropdown.innerHTML = companies[transportMode]
.map(company => `<option
value="${company}">${company}</option>`).join('');
}

else {
companiesDropdown.innerHTML = '';
}
}

function submitForm() {
const form = document.getElementById("bookingForm");
const data = new FormData(form);
const details = `
Booking Details:
Name: ${data.get('travelerName')}
Destination: ${data.get('destination')}
Travel Date: ${data.get('travelDate')}
Number of Travelers: ${data.get('numTravelers')}
Transport Mode: ${data.get('transportMode')}
Selected Company: ${data.get('companyList')}
`;
alert(details);
}
</script>
</head>
<body>
<h1>Travel Booking Form</h1>
<form id="bookingForm" onsubmit="submitForm();">
<label>Traveler Name: <input type="text" name="travelerName"
required></label><br><br>
<label>Destination: <input type="text" name="destination"
required></label><br><br>
<label>Travel Date: <input type="date" name="travelDate"
required></label><br><br>
<label>Number of Travelers: <input type="number"
name="numTravelers" min="1" required></label><br><br>
<label>Mode of Transport:
<select name="transportMode" id="transportMode"
onchange="updateCompanies()" required>
<option value="" disabled selected>Select</option>
<option value="Air">Air</option>
<option value="Train">Train</option>
<option value="Bus">Bus</option>
</select>
</label><br><br>
<label>Transport Company:
<select name="companyList" id="companyList" required>
<option value="" disabled selected>Select</option>
</select>
</label><br><br>
<button type="submit">Submit Booking</button>
</form>
</body>
</html>

Design a form with a dropdown to select a fruit (e.g., Apple, Banana) and
17 a quantity (text input). Include a button that changes the background
color based on the selected fruit and displays the chosen fruit and
quantity below the form.

<!DOCTYPE html>
<html lang="en">
<head>
<script>
function updateBackgroundAndDisplay() {
let selectedFruit = document.getElementById("fruit").value;
let quantity = document.getElementById("quantity").value;
let outputDiv = document.getElementById("output");
let color = "";
if (selectedFruit === "Apple") {
color = "lightcoral";
} else if (selectedFruit === "Banana") {
color = "lightyellow";
} else if (selectedFruit === "Orange") {
color = "lightorange";
}

document.body.style.backgroundColor = color;

outputDiv.innerHTML = `<p>You selected


<strong>${selectedFruit}</strong> with a quantity of
<strong>${quantity}</strong>.</p>`;
}
</script>
</head>
<body>

<h1>Fruit Selection Form</h1>

<form>
<label for="fruit">Select a fruit:</label>
<select id="fruit">
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Orange">Orange</option>
</select><br><br>
<label for="quantity">Enter quantity:</label>
<input type="text" id="quantity" placeholder="Enter
quantity"><br><br>

<button type="button"
onclick="updateBackgroundAndDisplay()">Submit</button>
</form>

<div id="output"></div>

</body>
</html>

Create a quiz form that features a question with multiple radio button
18 options (e.g., favorite hobby, favorite game, etc.) and a text input for the
user’s name. Validate that an option is selected before displaying a
summary of the inputs upon submission.

<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submitQuiz() {
const name = document.getElementById("name").value;
const favoriteHobby =
document.querySelector('input[name="hobby"]:checked');

const summary = `Hello ${name},<br>Your favorite hobby is:


${favoriteHobby.value}`;
document.getElementById("summary").innerHTML = summary;
}
</script>
</head>
<body>
<h1>Quiz Form</h1>

<form>
<label>Your Name: <input type="text" id="name"
required></label><br><br>

<p>Your favorite hobby:</p>


<label><input type="radio" name="hobby" value="Reading">
Reading</label><br>
<label><input type="radio" name="hobby" value="Sports">
Sports</label><br>
<label><input type="radio" name="hobby" value="Music">
Music</label><br><br>

<button type="button" onclick="submitQuiz()">Submit</button>


</form>

<div id="summary"></div>
</body>
</html>

Write a pet adoption form with text inputs for Applicant Name and
19 Contact Number, a dropdown for Pet Type (e.g., Dog, Cat), and a text
area for additional information. Upon submission, display the entered
details along with a message based on the selected pet type.

<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submitForm() {
const name = document.getElementById("applicantName").value;
const contact =
document.getElementById("contactNumber").value;
const pet = document.getElementById("petType").value;
const info = document.getElementById("additionalInfo").value;

let message = `Applicant: ${name}<br>Contact:


${contact}<br>Pet: ${pet}<br>Info: ${info}`;

if (pet === "Dog") {


message += "<br><strong>Thank you for considering adopting
a dog!</strong>";
} else if (pet === "Cat") {
message += "<br><strong>Thank you for considering adopting
a cat!</strong>";
}

document.getElementById("formSummary").innerHTML =
message;
}
</script>
</head>
<body>

<h1>Pet Adoption Form</h1>

<form>
<label>Name: <input type="text" id="applicantName"
required></label><br><br>
<label>Contact: <input type="text" id="contactNumber"
required></label><br><br>
<label>Pet Type:
<select id="petType" required>
<option value="" disabled selected>Select a pet</option>
<option value="Dog">Dog</option>
<option value="Cat">Cat</option>
</select>
</label><br><br>
<label>Additional Info:</label><br>
<textarea id="additionalInfo" placeholder="Any additional
details..."></textarea><br><br>

<button type="button" onclick="submitForm()">Submit</button>


</form>

<div id="formSummary" style="margin-top: 20px;"></div>

</body>
</html>

Write a program where a button changes its text to "Hovered!" and


20 background color of pages changes when the mouse is over it and button
text changes back to "Click Me!" and background color becomes white
again when the mouse leaves.

<!DOCTYPE html>
<html lang="en">
<head>
<script>
function onHover() {
document.getElementById("myButton").innerText = "Hovered!";
document.body.style.backgroundColor = "#f0f8ff";
}

function onLeave() {
document.getElementById("myButton").innerText = "Click Me!";
document.body.style.backgroundColor = "white";
}
</script>
</head>
<body>

<h1>Hover over the button</h1>

<button id="myButton" onmouseover="onHover()"


onmouseout="onLeave()">Click Me!</button>

</body>
</html>

Develop a form with several input fields. Write JavaScript code that
21 changes the border color of an input field to green when it gains focus and
to red when it loses focus (blur).

<!DOCTYPE html>
<html>
<head>
<script>
const inputs = document.querySelectorAll('input');

inputs.forEach(input => {
input.addEventListener('focus', () => {
input.style.border = '2px solid green';
input.style.outline = 'none';
});

input.addEventListener('blur', () => {
input.style.border = '2px solid red';
});
});
</script>
</head>
<body>
<h1>Form with Focus and Blur Events</h1>
<form>
<label for="name">Name:</label>
<input type="text" id="name”>
<br><br>
<label for="email">Email:</l
Write a JavaScript function that listens for the keydown event on an input
22 box. When a key is pressed, log the key's value to the console.

Develop an input box that counts the number of characters entered. Write
23 JavaScript code that listens for the input event and updates a paragraph
with the character count in real-time.

<!DOCTYPE html>
<html lang="en">
<body>
<h1>Character Counter</h1>
<label for="inputBox">Type something:</label><br>
<input type="text" id="inputBox" placeholder="Start typing...">
<p id="charCount">Character Count: 0</p>

<script>
const inputBox = document.getElementById("inputBox");
const charCount = document.getElementById("charCount");

inputBox.addEventListener("input", function () {
charCount.textContent = "Character Count: " + inputBox.value.length;
});
</script>
</body>
</html>

24 Write a JS to implement keyevents on an inputbox


<!DOCTYPE html>
<html lang="en">
<body>
<h1>Key Events on Input Box</h1>
<p>Type something in the input box below to see key event logs:</p>
<!-- Input box -->
<input type="text" id="keyInput" placeholder="Start typing..." />
<!-- Paragraph to display key event logs -->
<p id="log"></p>
<script>
const inputBox = document.getElementById('keyInput');
const log = document.getElementById('log');
function logEvent(eventType, event) {
log.innerHTML = `<strong>${eventType}:</strong> Key:
${event.key}, Code: ${event.code}`;
console.log(`${eventType}: Key: ${event.key}, Code:
${event.code}`);
}
inputBox.addEventListener('keydown', (event) =>
logEvent('keydown', event));
inputBox.addEventListener('keyup', (event) => logEvent('keyup',
event));
</script>
</body>
</html>

Write a JS Program to create a window with mouse events. Implement


25 mouse events like on click, on double click, on mouse down, on mouse
up, on mouse move.

<!DOCTYPE html>
<html lang="en">
<body>

<h1>Mouse Events Demonstration</h1>


<p>Interact with the area below to see mouse events in action:</p>

<!-- Area to detect mouse events -->


<div id="mouseArea" width="100%" height="300px">
Mouse Events Area (Click, Double Click, Mouse Down, Mouse Up,
Mouse Move)
</div>

<!-- Paragraph to display event info -->


<p id="eventInfo"></p>

<script>
const mouseArea = document.getElementById('mouseArea');
const eventInfo = document.getElementById('eventInfo');

function logEvent(eventType, event) {


eventInfo.innerHTML = `<strong>${eventType}</strong> at
Coordinates (X: ${event.clientX}, Y: ${event.clientY})`;
console.log(`${eventType}: X: ${event.clientX}, Y:
${event.clientY}`);
}

// Adding Mouse Events to the mouseArea

// Mouse Click event


mouseArea.addEventListener('click', function(event) {
logEvent('Click', event);
});

// Mouse Double Click event


mouseArea.addEventListener('dblclick', function(event) {
logEvent('Double Click', event);
});

// Mouse Down event (button pressed)


mouseArea.addEventListener('mousedown', function(event) {
logEvent('Mouse Down', event);
});

// Mouse Up event (button released)


mouseArea.addEventListener('mouseup', function(event) {
logEvent('Mouse Up', event);
});

// Mouse Move event (track the mouse movement)


mouseArea.addEventListener('mousemove', function(event) {
logEvent('Mouse Move', event);
});
</script>

</body>
</html>

Write a JS Program to create a textbox and 2 drop-down menus. The 2


26 drop-down menu's will have options of different font- styles and font-sizes
respectively. The font-style and font-size of the text inside the textbox
should change dynamically on change of either of the drop-down menu
selections.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Font Style and Size Modifier</title>
</head>
<body>

<h2>Modify Text Style and Size</h2>

<!-- Textbox where font style and size will change -->
<input type="text" id="textbox" value="Sample Text" size="30">

<br><br>

<!-- Dropdown for selecting font style -->


<label for="fontStyle">Choose Font Style:</label>
<select id="fontStyle">
<option value="Arial">Arial</option>
<option value="Courier New">Courier New</option>
<option value="Georgia">Georgia</option>
<option value="Times

Create a web page with a set of radio buttons that allow users to select a
28 category of options (e.g., Fruits, Vegetables, or Grains). Depending on the
selected category, dynamically generate corresponding checkbox options.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Dynamic Checkbox Generation</title>
<script>
// Function to update checkboxes based on the selected category
function updateOptions() {
// Get the selected category
var category =
document.querySelector('input[name="category"]:checked').value;
var optionsContainer = document.getElementById('options');
// Clear previous options
optionsContainer.innerHTML = '';

// Dynamically generate checkboxes based on the selected category


if (category === 'fruits') {
var fruits = ['Apple', 'Banana', 'Orange', 'Mango'];
fruits.forEach(function(fruit) {
var label = document.createElement('label');
label.innerHTML = `<input type="checkbox" name="fruit"
value="${fruit}"> ${fruit}<br>`;
optionsContainer.appendChild(label);
});
} else if (category === 'vegetables') {
var vegetables = ['Carrot', 'Broccoli', 'Spinach', 'Potato'];
vegetables.forEach(function(vegetable) {
var label = document.createElement('label');
label.innerHTML = `<input type="checkbox"
name="vegetable" value="${vegetable}"> ${vegetable}<br>`;
optionsContainer.appendChild(label);
});
} else if (category === 'grains') {
var grains = ['Rice', 'Wheat', 'Oats', 'Barley'];
grains.forEach(function(grain) {
var label = document.createElement('label');
label.innerHTML = `<input type="checkbox" name="grain"
value="${grain}"> ${grain}<br>`;
optionsContainer.appendChild(label);
});
}
}
</script>
</head>
<body>

<h2>Select a Category</h2>

<!-- Radio buttons for category selection -->


<input type="radio" name="category" value="fruits" id="fruits"
onclick="updateOptions()"> Fruits<br>
<input type="radio" name="category" value="vegetables"
id="vegetables" onclick="updateOptions()"> Vegetables<br>
<input type="radio" name="category" value="grains" id="grains"
onclick="updateOptions()"> Grains<br>
<div id="options" style="margin-top: 20px;">
<!-- Dynamically generated checkboxes will appear here -->
</div>

</body>
</html>

Design a simple survey form using HTML and JavaScript that includes
29 two radio buttons ("Yes" and "No"), a checkbox for "Subscribe to
newsletter," and a "Submit" button. Upon clicking the "Submit" button,
display a thank you message in a read-only textarea based on the user's
selections.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Survey Form</title>
<script>
// Function to handle the form submission and display the thank you
message
function submitForm() {
// Get the value of the "Yes" or "No" radio button
var yesNoAnswer =
document.querySelector('input[name="survey"]:checked');
if (!yesNoAnswer) {
alert("Please select Yes or No.");
return;
}

// Get the value of the checkbox for "Subscribe to newsletter"


var subscribe = document.getElementById('subscribe').checked;

// Generate the thank you message


var message = "Thank you for your response!\n\n";
message += "You answered: " + yesNoAnswer.value + "\n";
message += "Subscribe to newsletter: " + (subscribe ? "Yes" :
"No");
// Display the message in the read-only textarea
document.getElementById('thankyouMessage').value = message;
}
</script>
</head>
<body>

<h2>Survey Form</h2>

<!-- Survey question with radio buttons -->


<p>Do you like JavaScript?</p>
<input type="radio" name="survey" value="Yes" id="yes"> Yes
<input type="radio" name="survey" value="No" id="no"> No

<br><br>

<!-- Checkbox for subscription -->


<input type="checkbox" id="subscribe"> Subscribe to newsletter

<br><br>

<!-- Submit button -->


<button onclick="submitForm()">Submit</button>

<br><br>

<!-- Textarea to display the thank you message -->


<textarea id="thankyouMessage" rows="6" cols="50"
readonly></textarea>

</body>
</html>

Create a JavaScript program that changes the text of a label based on the
30 value of an input field as the user types. The label should update in
real-time to reflect the current input. Use an image instead of button to
implement intrensic function.
Write a JS Program to create a student registration form. Accept the
31 following details: StudentName, StudentAge, StudentPhoneNumber.
Use a drop-down menu to allow the user to select their year.
Dynamically change the item of the next drop-down menu to allow the
user to choose the semester. Use an image instead of button to
implement intrensic function.

<!DOCTYPE html>
<html lang="en">
<body>
<div class="form-container">
<h2>Student Registration</h2>
<form id="registrationForm">
<label for="studentName">Student Name:</label>
<input type="text" id="studentName" name="studentName"
required>

<label for="studentAge">Student Age:</label>


<input type="number" id="studentAge" name="studentAge"
required>

<label for="studentPhone">Student Phone Number:</label>


<input type="tel" id="studentPhone" name="studentPhone"
required>

<label for="year">Year:</label>
<select id="year" name="year"
onchange="updateSemesterOptions()" required>
<option value="">Select Year</option>
<option value="1">First Year</option>
<option value="2">Second Year</option>
<option value="3">Third Year</option>
<option value="4">Fourth Year</option>
</select>

<label for="semester">Semester:</label>
<select id="semester" name="semester" required>
<option value="">Select Semester</option>
</select>

<br>
<img src="https://via.placeholder.com/30" alt="Submit"
onclick="submitForm()">
</form>
</div>

<script>
function updateSemesterOptions() {
const year = document.getElementById('year').value;
const semesterDropdown = document.getElementById('semester');

semesterDropdown.innerHTML = '<option value="">Select


Semester</option>';

let semesters = [];

if (year === "1") {


semesters = ["Semester 1", "Semester 2"];
} else if (year === "2") {
semesters = ["Semester 3", "Semester 4”];
} else if (year === "3") {
semesters = ["Semester 5", "Semester 6”];
} else if (year === "4") {
semesters = ["Semester 7", "Semester 8"];
}

semesters.forEach(semester => {
const option = document.createElement("option");
option.value = semester;
option.textContent = semester;
semesterDropdown.appendChild(option);
});
}

function submitForm() {
const form = document.getElementById('registrationForm');
const studentName =
document.getElementById('studentName').value;
const studentAge = document.getElementById('studentAge').value;
const studentPhone =
document.getElementById('studentPhone').value;
const year = document.getElementById('year').value;
const semester = document.getElementById('semester').value;

if (!studentName || !studentAge || !studentPhone || !year || !semester)


{
alert("Please fill out all the fields.");
return;
}

alert(`Student Registered!\nName: ${studentName}\nAge:


${studentAge}\nPhone: ${studentPhone}\nYear: ${year}\nSemester:
${semester}`);
form.reset();
}
</script>
</body>
</html>

32 Write a JS Program to implement all concepts of cookies, namely: Create,


Read and Delete.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Cookie Operations</title>
<script>
// Function to create a cookie
function createCookie(name, value, days) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); //
Set expiry in days
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + encodeURIComponent(value) +
expires + "; path=/";
alert("Cookie created: " + name + "=" + value);
}
// Function to read a cookie
function readCookie(name) {
const nameEQ = name + "=";
const cookiesArray = document.cookie.split(';');
for (let i = 0; i < cookiesArray.length; i++) {
let cookie = cookiesArray[i].trim();
if (cookie.indexOf(nameEQ) === 0) {
return
decodeURIComponent(cookie.substring(nameEQ.length));
}
}
return null; // Return null if cookie is not found
}
// Function to delete a cookie
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00
UTC; path=/";
alert("Cookie deleted: " + name);
}
// Handle button clicks to perform operations
function handleCreate() {
const name =
document.getElementById("cookieName").value.trim();
const value =
document.getElementById("cookieValue").value.trim();
const days =
parseInt(document.getElementById("cookieDays").value) || 0;
if (!name) {
alert("Please enter a cookie name.");
return;
}
createCookie(name, value, days);
}
function handleRead() {
const name =
document.getElementById("cookieName").value.trim();
if (!name) {
alert("Please enter the cookie name to read.");
return;
}
const result = readCookie(name);
if (result) {
alert("Cookie value: " + result);
} else {
alert("Cookie not found! Make sure you have created it.");
}
}
function handleDelete() {
const name =
document.getElementById("cookieName").value.trim();
if (!name) {
alert("Please enter the cookie name to delete.");
return;
}
deleteCookie(name);
}
</script>
</head>
<body>
<h1>Cookie Operations</h1>
<form onsubmit="return false;">
<label for="cookieName">Cookie Name:</label>
<input type="text" id="cookieName" placeholder="Enter cookie
name" required><br><br>
<label for="cookieValue">Cookie Value:</label>
<input type="text" id="cookieValue" placeholder="Enter cookie
value"><br><br>
<label for="cookieDays">Expiry Days:</label>
<input type="number" id="cookieDays" placeholder="Enter expiry in
days"><br><br>
<button onclick="handleCreate()">Create Cookie</button>
<button onclick="handleRead()">Read Cookie</button>
<button onclick="handleDelete()">Delete Cookie</button>
</form>
</body>
</html>
ISME COOKIE READ NHI HO RAHA HAI
Write a JS Program to implement window functions like: resizeBy,
33 resizeTo, scrollBy, scrollTo, moveBy, moveTo, open a window on the
same tab, open the window on a new tab and open a window on a new
page.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Window Functions Demo</title>
<script>
// Resize the window by the specified width and height
function resizeByExample() {
window.resizeBy(100, 100); // Increase the window by 100px in
width and height
alert("Window resized by 100px in both directions.");
}

// Resize the window to the specified width and height


function resizeToExample() {
window.resizeTo(800, 600); // Resize the window to 800px by
600px
alert("Window resized to 800px x 600px.");
}

// Scroll the window by the specified number of pixels


function scrollByExample() {
window.scrollBy(0, 100); // Scroll down by 100px
alert("Window scrolled down by 100px.");
}
// Scroll the window to a specific position
function scrollToExample() {
window.scrollTo(0, 0); // Scroll to the top of the page
alert("Window scrolled to the top.");
}

// Move the window by the specified pixels


function moveByExample() {
window.moveBy(50, 50); // Move the window 50px to the right
and 50px down
alert("Window moved by 50px in both directions.");
}

// Move the window to a specific position on the screen


function moveToExample() {
window.moveTo(200, 200); // Move the window to position
(200px, 200px) on the screen
alert("Window moved to position (200, 200).");
}

// Open a new window in the same tab


function openSameTab() {
window.location.href = "https://www.example.com"; // Replace
current tab's URL
}

// Open a new window in a new tab


function openNewTab() {
window.open("https://www.example.com", "_blank"); // Open
URL in a new tab
}

// Open a window as a new popup


function openNewWindow() {
window.open("https://www.example.com", "_blank",
"width=600,height=400"); // Open as a popup window
}
</script>
</head>
<body>
<h1>Window Functions Demonstration</h1>
<button onclick="resizeByExample()">Resize By</button>
<button onclick="resizeToExample()">Resize To</button>
<button onclick="scrollByExample()">Scroll By</button>
<button onclick="scrollToExample()">Scroll To</button>
<button onclick="moveByExample()">Move By</button>
<button onclick="moveToExample()">Move To</button>
<button onclick="openSameTab()">Open Same Tab</button>
<button onclick="openNewTab()">Open New Tab</button>
<button onclick="openNewWindow()">Open New Window</button>
</body>
</html>
Write a javscript that displays a form that contains an input for username
34 & password. User is prompted to enter the input & password & password
becomes the value of the cookie. Write a JavaScript function for storing
the cookie. It gets executed when the password changes.
Write a JavaScript program that creates a cookie called lastVisit which
35 stores the current date and time. The cookie should expire in 14 days.
Also, demonstrate how to read this cookie value and display it on the web
page.
Write a JavaScript function that opens a new browser window with a
36 specific URL(any URL available), width, and height on a Button Click.
The function should also set the window's position on the screen. Ensure
that window is brought on focus when it is opened.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Open New Window</title>
<script>
// Function to open a new window
function openWindow() {
// URL of the new window
const url = "https://ves.ac.in/polytechnic/"; // You can change this
to any URL

// Window properties
const width = 500;
const height = 400;
const left = 100; // Position from left side of the screen
const top = 100; // Position from top of the screen

// Open the new window


const newWindow = window.open(
url,
"_blank", // Open in a new window
`width=${width}, height=${height}, left=${left}, top=${top}`
);

// Bring the new window into focus


if (newWindow) {
newWindow.focus();
}
}
</script>
</head>
<body>
<h1>Open a New Window Example</h1>
<button onclick="openWindow()">Open Window</button>
</body>
</html>

Create a function that opens three new browser windows with different
37 URLs: one for a search engine (e.g., Google), one for a social media site
(e.g., Facebook), and one for a news site (e.g., BBC). Use setTimeout to
focus each window in sequence with a delay of 3 seconds between each
focus action.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Open and Focus Windows</title>
</head>
<body>
<h1>Open and Focus Windows Example</h1>
<button onclick="openAndFocusWindows()">Open and Focus
Windows</button>

<script>
function openAndFocusWindows() {
// Open three different windows with specified URLs
let googleWindow = window.open("https://www.google.com",
"_blank");
let facebookWindow = window.open("https://www.facebook.com",
"_blank");
let bbcWindow = window.open("https://www.bbc.com", "_blank");

// Set timeouts to focus each window with a 3-second delay


setTimeout(function() {
googleWindow.focus(); // Focus on Google window
}, 3000);

setTimeout(function() {
facebookWindow.focus(); // Focus on Facebook window
}, 6000);

setTimeout(function() {
bbcWindow.focus(); // Focus on BBC window
}, 9000);
}
</script>
</body>
</html>

38 Write a JavaScript function to check whether a given address is a valid IP


address or not.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>IP Address Validator</title>
</head>
<body>
<h1>IP Address Validator</h1>
<label for="ipAddress">Enter IP Address:</label>
<input type="text" id="ipAddress" placeholder="Enter an IP address">
<button onclick="validateIP()">Check Validity</button>
<p id="result"></p>
<script>
function isValidIPAddress(ip) {
// Regular expression for validating IPv4
const ipv4Pattern =
/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-
9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9
][0-9]?)$/;
// Regular expression for validating IPv6
const ipv6Pattern = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
// Check if the input matches IPv4 or IPv6 pattern
return ipv4Pattern.test(ip) || ipv6Pattern.test(ip);
}
function validateIP() {
// Get the input IP address from the text box
const ipAddress = document.getElementById('ipAddress').value;
// Get the result element to display the validation message
const result = document.getElementById('result');
// Validate the IP address
if (isValidIPAddress(ipAddress)) {
result.textContent = `"${ipAddress}" is a valid IP address.`;
result.style.color = 'green';
} else {
result.textContent = `"${ipAddress}" is not a valid IP address.`;
result.style.color = 'red';
}
}
</script>
</body>
</html>

Create a script that sets a cookie with a specific expiration date (e.g., 30
39 days from now) and displays a message indicating when the cookie will
expire.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Cookie Expiration Example</title>
</head>
<body>
<h1>Cookie Expiration Example</h1>

<p id="cookieMessage"></p>

<script>
// Function to set a cookie with a specific expiration date
function setCookie(name, value, days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); //
Calculate expiration date
const expires = "expires=" + date.toUTCString(); // Format
expiration date to UTC string
document.cookie = `${name}=${value}; ${expires}; path=/`; //
Set the cookie
}

// Function to get a specific cookie value by its name


function getCookie(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i].trim();
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null;
}

// Function to display cookie expiration message


function displayCookieExpirationMessage() {
// Set a cookie with a 30-day expiration
setCookie("userVisit", "true", 30);

// Get the current date and calculate the expiration date


const currentDate = new Date();
const expirationDate = new Date();
expirationDate.setTime(currentDate.getTime() + (30 * 24 * 60 *
60 * 1000)); // 30 days from now

// Display the expiration date in a human-readable format


const expirationMessage = `The "userVisit" cookie will expire on:
${expirationDate.toUTCString()}.`;

// Show the message on the page


document.getElementById("cookieMessage").textContent =
expirationMessage;
}

// Call the function to set the cookie and display the expiration
message
displayCookieExpirationMessage();
</script>
</body>
</html>

40 Write a script that opens a new window and with a heading, a


paragraph.close the window using button.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Open and Close Window</title>
</head>
<body>
<h1>Open and Close Window Example</h1>
<button onclick="openNewWindow()">Open New Window</button>
<script>
let newWindow = null;
function openNewWindow() {
// Open a new window
newWindow = window.open('', '_blank', 'width=400, height=300');
// Write content to the new window
newWindow.document.write(`
<h1>Welcome to the New Window</h1>
<p>This is a paragraph inside the new window.</p>
<button onclick="window.close()">Close Window</button>
`);
// Optional: You can close the window after some time if desired
(e.g., after 10 seconds)
// setTimeout(() => {
// newWindow.close();
// }, 10000);
}
</script>
</body>
</html>

Create a JavaScript application with two buttons: the first opens a window
41 displaying the current date in DD/MM/YYYY format, and the second
opens another window displaying all prime numbers between 1 and 50.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Simple App</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
button {
font-size: 16px;
padding: 10px 20px;
margin: 10px;
border-radius: 5px;
background-color: #4CAF50;
color: white;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<button onclick="showDate()">Show Current Date</button>
<button onclick="showPrimes()">Show Prime Numbers</button>

<script>
function showDate() {
const now = new Date();
const date = now.getDate() + "/" + (now.getMonth() + 1) + "/" +
now.getFullYear();
const dateWindow = window.open("", "DateWindow",
"width=200,height=100");
dateWindow.document.write("<h1 style='font-family: Arial;
text-align: center;'>Current Date</h1>");
dateWindow.document.write("<p style='text-align: center;'>" +
date + "</p>");
}

function showPrimes() {
let primes = "";
for (let i = 2; i <= 50; i++) {
let isPrime = true;
for (let j = 2; j < i; j++) {
if (i % j === 0) {
isPrime = false;
break;
}
}
if (isPrime) primes += i + " ";
}
const primesWindow = window.open("", "PrimesWindow",
"width=300,height=200");
primesWindow.document.write("<h1 style='font-family: Arial;
text-align: center;'>Prime Numbers (1-50)</h1>");
primesWindow.document.write("<p style='text-align: center;'>" +
primes + "</p>");
}
</script>
</body>
</html>
42
43 Write a javascript to create option list containing list of images and then
display images in new window as per selection.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Image Selector</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
select, button {
font-size: 16px;
padding: 10px;
margin: 10px;
}
button {
border: none;
border-radius: 5px;
background-color: #4CAF50;
color: white;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<h1>Select an Image</h1>
<select id="imageSelector">
<option value="">-- Select an Image --</option>
<option value="https://via.placeholder.com/150">Image 1</option>
<option value="https://via.placeholder.com/200">Image 2</option>
<option value="https://via.placeholder.com/250">Image 3</option>
</select>
<button onclick="showImage()">Show Image</button>
<script>
function showImage() {
const imageUrl =
document.getElementById("imageSelector").value;
if (!imageUrl) {
alert("Please select an image.");
return;
}
const imageWindow = window.open("", "ImageWindow",
"width=400,height=400");
imageWindow.document.body.innerHTML = `<h1>Selected
Image</h1><img src="${imageUrl}" style="max-width:100%;">`;
}
</script>
</body>
</html>

Write a JS program that validates a strong password. The password must


44 be at least 8 characters long, contain at least one uppercase letter, one
lowercase letter, one digit, and one special character.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Password Validator</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input, button {
font-size: 16px;
padding: 10px;
margin: 10px;
}
button {
border: none;
border-radius: 5px;
background-color: #4CAF50;
color: white;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.message {
font-size: 16px;
color: red;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Password Validator</h1>
<input type="password" id="password" placeholder="Enter your
password">
<button onclick="validatePassword()">Validate</button>
<p id="message" class="message"></p>

<script>
function validatePassword() {
const password = document.getElementById("password").value;
const message = document.getElementById("message");

// Regular expression for a strong password


const strongPasswordRegex =
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{
8,}$/;

if (strongPasswordRegex.test(password)) {
message.style.color = "green";
message.textContent = "Password is strong!";
} else {
message.style.color = "red";
message.textContent = "Password must be at least 8 characters
long, include at least one uppercase letter, one lowercase letter, one digit,
and one special character.";
}
}
</script>
</body>
</html>
Write a JS program that validates a phone number based on the following
45 criteria: it must be 10 digits long and may start with 7, 8, or 9.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Phone Number Validator</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input, button {
font-size: 16px;
padding: 10px;
margin: 10px;
}
button {
border: none;
border-radius: 5px;
background-color: #4CAF50;
color: white;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.message {
font-size: 16px;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Phone Number Validator</h1>
<input type="text" id="phoneNumber" placeholder="Enter phone
number">
<button onclick="validatePhoneNumber()">Validate</button>
<p id="message" class="message"></p>

<script>
function validatePhoneNumber() {
const phoneNumber =
document.getElementById("phoneNumber").value;
const message = document.getElementById("message");

// Regular expression for phone number validation


const phoneRegex = /^[789]\d{9}$/;

if (phoneRegex.test(phoneNumber)) {
message.style.color = "green";
message.textContent = "Phone number is valid!";
} else {
message.style.color = "red";
message.textContent = "Invalid phone number. It must be 10
digits long and start with 7, 8, or 9.";
}
}
</script>
</body>
</html>
Write a JS program that validates a date in the format DD/MM/YYYY
46
47 Write a JavaScript program that will print even numbers from 1to 20
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Even Numbers</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
text-align: center;
margin-top: 50px;
}
h1 {
color: #4CAF50;
}
p{
font-size: 18px;
font-weight: bold;
color: #333;
}
#evenNumbers {
font-size: 20px;
color: #007BFF;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Even Numbers from 1 to 20</h1>
<p id="evenNumbers"></p>
<script>
let evenNumbers = "";
for (let i = 2; i <= 20; i += 2) {
evenNumbers += i + " ";
}
document.getElementById("evenNumbers").textContent =
evenNumbers;
</script>
</body>
</html>
Write a JS Program to create a textbox which will accept numbers,
48 decimal point up to 2 digits and positive or negative sign. Eg:
+123.22 is a valid number, but +123a.22 is invalid.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Number Validation</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input, button {
font-size: 16px;
padding: 10px;
margin: 10px;
}
button {
border: none;
border-radius: 5px;
background-color: #4CAF50;
color: white;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.message {
font-size: 16px;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Number Validator</h1>
<input type="text" id="numberInput" placeholder="Enter number
(+/-)123.45">
<button onclick="validateNumber()">Validate</button>
<p id="message" class="message"></p>
<script>
function validateNumber() {
const input = document.getElementById("numberInput").value;
const message = document.getElementById("message");
// Regular expression to match valid numbers: optional + or - sign,
digits, decimal point, and 2 digits after the decimal
const regex = /^[+-]?(\d+(\.\d{1,2})?)$/;
if (regex.test(input)) {
message.textContent = "Valid number!";
message.style.color = "green";
} else {
message.textContent = "Invalid number. Please enter a valid
number (+/-)123.45 format.";
message.style.color = "red";
}
}
</script>
</body>
</html>

Write a JS Program to create a regex which will perform a global,


49 multi-line, and case-sensitive match for some user-defined text in a
textarea.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Regex Matcher</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
background-color: #f4f4f9;
}
h1 {
color: #333;
}
textarea, input {
font-size: 16px;
padding: 10px;
margin: 10px;
width: 300px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
font-size: 16px;
padding: 10px 20px;
margin: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
p{
font-size: 16px;
margin-top: 20px;
color: #333;
}
</style>
</head>
<body>
<h1>Regex Matcher</h1>
<textarea id="textInput" placeholder="Enter text
here"></textarea><br>
<input type="text" id="patternInput" placeholder="Enter regex
pattern"><br>
<button onclick="matchPattern()">Search</button>
<p id="message"></p>

<script>
function matchPattern() {
const text = document.getElementById("textInput").value;
const pattern = document.getElementById("patternInput").value;
const regex = new RegExp(pattern, "gm");
const matches = text.match(regex);
document.getElementById("message").textContent = matches ?
`${matches.length} match(es) found.` : "No matches found.";
}
</script>
</body>
</html>
Write a JS Program to create a regex expression that will check the
50 number of times the vowels has been arrived in a sentence. Accept the
sentence from the user.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Vowel Counter</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
textarea, input {
font-size: 16px;
padding: 10px;
margin: 10px;
width: 300px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
font-size: 16px;
padding: 10px 20px;
margin: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
p{
font-size: 16px;
margin-top: 20px;
color: #333;
}
</style>
</head>
<body>
<h1>Vowel Counter</h1>
<textarea id="sentenceInput" placeholder="Enter a
sentence"></textarea><br>
<button onclick="countVowels()">Count Vowels</button>
<p id="message"></p>

<script>
function countVowels() {
const sentence =
document.getElementById("sentenceInput").value;
const regex = /[aeiouAEIOU]/g; // Regex to match vowels
(case-insensitive)
const matches = sentence.match(regex); // Find all vowel matches

const vowelCount = matches ? matches.length : 0; // Count the


vowels, or return 0 if no vowels found
document.getElementById("message").textContent = `Vowels
found: ${vowelCount}`;
}
</script>
</body>
</html>
51 Write a JavaScript function to validate Permanent Account Numbers
(PAN).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>PAN Validator</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input, button {
font-size: 16px;
padding: 10px;
margin: 10px;
width: 300px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.message {
font-size: 16px;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>PAN Number Validator</h1>
<input type="text" id="panInput" placeholder="Enter PAN (e.g.
ABCDE1234F)">
<button onclick="validatePAN()">Validate PAN</button>
<p id="message" class="message"></p>
<script>
function validatePAN() {
const pan = document.getElementById("panInput").value;
const regex = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/; // Regex pattern for
PAN
const message = document.getElementById("message");
if (regex.test(pan)) {
message.textContent = "Valid PAN Number!";
message.style.color = "green";
} else {
message.textContent = "Invalid PAN Number. Please enter a
valid PAN.";
message.style.color = "red";
}
}
</script>
</body>
</html>
Write a javascript program to design HTML page with books information
52 Book name and its price in tabular format, use rollovers to display the
discounted price at the place of original price

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Books Information</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
table {
width: 50%;
margin: auto;
border-collapse: collapse;
}
th, td {
padding: 10px;
border: 1px solid #ccc;
}
th {
background-color: #f4f4f4;
}
tr:hover {
background-color: #f9f9f9;
}
.price {
color: green;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Book Information</h1>
<table>
<thead>
<tr>
<th>Book Name</th>
<th>Original Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>JavaScript for Beginners</td>
<td class="price" onmouseover="showDiscount(this, 200)"
onmouseout="hideDiscount(this, 250)">₹250</td>
</tr>
<tr>
<td>Learn HTML and CSS</td>
<td class="price" onmouseover="showDiscount(this, 350)"
onmouseout="hideDiscount(this, 450)">₹450</td>
</tr>
<tr>
<td>Advanced JavaScript</td>
<td class="price" onmouseover="showDiscount(this, 300)"
onmouseout="hideDiscount(this, 400)">₹400</td>
</tr>
<tr>
<td>Python Programming</td>
<td class="price" onmouseover="showDiscount(this, 400)"
onmouseout="hideDiscount(this, 500)">₹500</td>
</tr>
</tbody>
</table>

<script>
// Function to show discounted price
function showDiscount(element, discountedPrice) {
element.textContent = "₹" + discountedPrice; // Update price to
discounted price
element.style.color = "red"; // Change text color to red to indicate
discount
}

// Function to hide discounted price and show original price


function hideDiscount(element, originalPrice) {
element.textContent = "₹" + originalPrice; // Reset to original
price
element.style.color = "green"; // Reset text color to green
}
</script>
</body>
</html>
53 Create a Rollover effect uisng 3-4 Images
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Image Rollover Effect</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
background-color: #f4f4f9;
}
.image-container {
display: flex;
justify-content: center;
gap: 20px;
}
.image-container img {
width: 200px;
height: 150px;
border-radius: 10px;
transition: transform 0.3s ease;
}
.image-container img:hover {
transform: scale(1.1);
}
</style>
</head>
<body>
<h1>Image Rollover Effect</h1>
<div class="image-container">
<img src="image1.jpg" alt="Image 1" id="img1"
onmouseover="changeImage(this, 'image1-hover.jpg')"
onmouseout="resetImage(this, 'image1.jpg')">
<img src="image2.jpg" alt="Image 2" id="img2"
onmouseover="changeImage(this, 'image2-hover.jpg')"
onmouseout="resetImage(this, 'image2.jpg')">
<img src="image3.jpg" alt="Image 3" id="img3"
onmouseover="changeImage(this, 'image3-hover.jpg')"
onmouseout="resetImage(this, 'image3.jpg')">
</div>
<script>
function changeImage(element, newSrc) {
element.src = newSrc; // Change image source to the new image
on hover
}
function resetImage(element, originalSrc) {
element.src = originalSrc; // Reset to the original image when the
mouse leaves
}
</script>
</body>
</html>
54 Write a JS Program to implement Text Rollover. There should be at least
10 texts to implement the concept.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Text Rollover Effect</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
background-color: #f4f4f9;
}
.text-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 15px;
}
.text-item {
font-size: 18px;
padding: 10px;
cursor: pointer;
transition: color 0.3s ease, transform 0.3s ease;
}
.text-item:hover {
color: #ff6347; /* Change to tomato color when hovered */
transform: scale(1.1); /* Slightly enlarge the text */
}
</style>
</head>
<body>
<h1>Text Rollover Effect</h1>
<div class="text-container">
<div class="text-item" onmouseover="changeText(this)"
onmouseout="resetText(this)">Text 1</div>
<div class="text-item" onmouseover="changeText(this)"
onmouseout="resetText(this)">Text 2</div>
<div class="text-item" onmouseover="changeText(this)"
onmouseout="resetText(this)">Text 3</div>
<div class="text-item" onmouseover="changeText(this)"
onmouseout="resetText(this)">Text 4</div>
<div class="text-item" onmouseover="changeText(this)"
onmouseout="resetText(this)">Text 5</div>
<div class="text-item" onmouseover="changeText(this)"
onmouseout="resetText(this)">Text 6</div>
<div class="text-item" onmouseover="changeText(this)"
onmouseout="resetText(this)">Text 7</div>
<div class="text-item" onmouseover="changeText(this)"
onmouseout="resetText(this)">Text 8</div>
<div class="text-item" onmouseover="changeText(this)"
onmouseout="resetText(this)">Text 9</div>
<div class="text-item" onmouseover="changeText(this)"
onmouseout="resetText(this)">Text 10</div>
</div>
<script>
// Function to change the color of the text when hovered
function changeText(element) {
element.style.color = "#ff6347"; // Change text color on hover
element.style.transform = "scale(1.1)"; // Slightly enlarge text on
hover
}
// Function to reset the color of the text when hover is removed
function resetText(element) {
element.style.color = ""; // Reset text color to default
element.style.transform = "scale(1)"; // Reset the scale to default
}
</script>
</body>
</html>
55 Write a JS to create a frameset with 4 cols and 2 rows each displaying
various pages or images.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Frameset Alternative</title>
<style>
body {
margin: 0;
display: grid;
grid-template-rows: 50% 50%;
grid-template-columns: 25% 25% 25% 25%;
height: 100vh;
}
iframe {
border: 1px solid #ccc;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<!-- Row 1 -->
<iframe src="https://example.com" title="Frame 1"></iframe>
<iframe src="https://www.wikipedia.org" title="Frame 2"></iframe>
<iframe src="https://www.google.com" title="Frame 3"></iframe>
<iframe src="https://www.github.com" title="Frame 4"></iframe>
<!-- Row 2 -->
<iframe src="image1.jpg" title="Image 1"></iframe>
<iframe src="image2.jpg" title="Image 2"></iframe>
<iframe src="image3.jpg" title="Image 3"></iframe>
<iframe src="image4.jpg" title="Image 4"></iframe>
</body>
</html>
Write a script for creating following frame structure : Frame 1 contains
three buttons SPORT, MUSIC and DANCE that will perform following
action : When user clicks SPORT button, sport.html webpage will appear
56 in Frame 2. When user clicks MUSIC button, music.html webpage will
appear in Frame 3. When user clicks DANCE button, dance.html
webpage will appear in Frame 4.

save with css code.html


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Interactive Frames</title>
<style>
body {
margin: 0;
display: grid;
grid-template-rows: 20% 40% 40%;
grid-template-columns: 50% 50%;
height: 100vh;
}
#frame1 {
grid-column: span 2;
background-color: #f4f4f9;
text-align: center;
display: flex;
align-items: center;
justify-content: center;
gap: 20px;
}
#frame1 button {
padding: 10px 20px;
font-size: 16px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
#frame1 button:hover {
background-color: #0056b3;
}
iframe {
border: 1px solid #ccc;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<!-- Frame 1: Contains Buttons -->
<div id="frame1">
<button onclick="loadContent('frame2',
'sport.html')">SPORT</button>
<button onclick="loadContent('frame3',
'music.html')">MUSIC</button>
<button onclick="loadContent('frame4',
'dance.html')">DANCE</button>
</div>

<!-- Frame 2: Sport -->


<iframe id="frame2" title="Frame 2"></iframe>

<!-- Frame 3: Music -->


<iframe id="frame3" title="Frame 3"></iframe>

<!-- Frame 4: Dance -->


<iframe id="frame4" title="Frame 4"></iframe>

<script>
function loadContent(frameId, url) {
document.getElementById(frameId).src = url;
}
</script>
</body>
</html>

save with sport.html


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sport</title>
</head>
<body>
<h1>Sport Page</h1>
<p>Welcome to the Sport section!</p>
</body>
</html>
save with music.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Music</title>
</head>
<body>
<h1>Music Page</h1>
<p>Welcome to the Music section!</p>
</body>
</html>
save with dance.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dance</title>
</head>
<body>
<h1>Dance Page</h1>
<p>Welcome to the Dance section!</p>
</body>
</html>

op me dekho thoda doubt h kyuki wo 3 buttons frame 1 me nahi place ho


rahe instead upar display hue hai uss wajah se 4th frame is empty.
chatgpt bhi sahi code nahi de raha toh sahi formatting wala mile toh
replace kardena
-xoxo khushi
Write a script for creating
following frame structure In
Frame 1 Add two frames
57 In frame 2 Display a list of links of html pages respectively. When these
links are clicked corresponding data appears in FRAME 3.

<!DOCTYPE html>
<html>
<head>
<title>Frameset Example with iframes</title>
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
}
#header {
height: 20%;
background-color: #f4f4f4;
text-align: center;
padding: 10px;
}
#container {
display: flex;
height: 80%;
}
#nav {
width: 30%;
background-color: #e8e8e8;
padding: 10px;
overflow-y: auto;
}
#content {
width: 70%;
}
iframe {
width: 100%;
height: 100%;
border: none;
}
a{
text-decoration: none;
color: blue;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<!-- Frame 1 -->
<div id="header">
<h1>Welcome to the Frameset Example</h1>
</div>

<!-- Frame 2 and Frame 3 -->


<div id="container">
<!-- Frame 2 -->
<div id="nav">
<h3>Navigation Links</h3>
<ul>
<li><a href="page1.html" target="content-frame">Page
1</a></li>
<li><a href="page2.html" target="content-frame">Page
2</a></li>
<li><a href="page3.html" target="content-frame">Page
3</a></li>
</ul>
</div>

<!-- Frame 3 -->


<div id="content">
<iframe name="content-frame" src="default.html"></iframe>
</div>
</div>
</body>
</html>

Content of header.html (for Frame 1)

This can display a simple header.

html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Header</title>
</head>
<body>
<h1>Welcome to the Frameset Example</h1>
</body>
</html>

Content of links.html (for Frame 2)

This file contains a list of links pointing to other HTML pages.

html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Links</title>
</head>
<body>
<h2>Navigation Links</h2>
<ul>
<li><a href="page1.html"
target="frame3">Page 1</a></li>
<li><a href="page2.html"
target="frame3">Page 2</a></li>
<li><a href="page3.html"
target="frame3">Page 3</a></li>
</ul>
</body>
</html>

Content of default.html (for Frame 3)

This is the default content displayed when no link is clicked.

html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Default Page</title>
</head>
<body>
<h2>Welcome to the content area</h2>
<p>Select a link from the navigation to view
the content.</p>
</body>
</html>

Content of page1.html, page2.html, page3.html (for Frame 3)

Each page contains specific content displayed when its link is clicked.
page1.html
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Page 1</title>
</head>
<body>
<h2>Page 1 Content</h2>
<p>This is the content of Page 1.</p>
</body>
</html>

page2.html
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Page 2</title>
</head>
<body>
<h2>Page 2 Content</h2>
<p>This is the content of Page 2.</p>
</body>
</html>
page3.html
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Page 3</title>
</head>
<body>
<h2>Page 3 Content</h2>
<p>This is the content of Page 3.</p>
</body>
</html>
58 Write a Java Script to demonstrate the use of Chain select menu.
<!DOCTYPE html>
<html>
<head>
<title>Simple Chain Select Menu with CSS</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f4f4f9;
}
h2 {
text-align: center;
color: #333;
}
label {
font-size: 16px;
color: #555;
margin-right: 10px;
}
select {
padding: 8px;
font-size: 16px;
width: 200px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
select:focus {
border-color: #007BFF;
outline: none;
}
.container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.select-wrapper {
margin: 20px;
padding: 10px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.select-wrapper label {
display: block;
margin-bottom: 8px;
}
</style>
<script>
function updateSubcategory() {
const subcategoryOptions =
document.querySelectorAll("#subcategory option");
const selectedCategory =
document.getElementById("category").value;
// Show relevant subcategories, hide others
subcategoryOptions.forEach(option => {
option.style.display = option.dataset.category ===
selectedCategory ? "block" : "none";
});
// Reset subcategory selection
document.getElementById("subcategory").value = "";
}
</script>
</head>
<body>
<div class="container">
<h2>Simple Chain Select Menu</h2>
<div class="select-wrapper">
<label for="category">Category:</label>
<select id="category" onchange="updateSubcategory()">
<option value="">Select Category</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
<option value="Animals">Animals</option>
</select>
</div>
<div class="select-wrapper">
<label for="subcategory">Subcategory:</label>
<select id="subcategory">
<option value="">Select Subcategory</option>
<option data-category="Fruits" value="Apple">Apple</option>
<option data-category="Fruits"
value="Banana">Banana</option>
<option data-category="Fruits"
value="Orange">Orange</option>
<option data-category="Vegetables"
value="Carrot">Carrot</option>
<option data-category="Vegetables"
value="Broccoli">Broccoli</option>
<option data-category="Vegetables"
value="Spinach">Spinach</option>
<option data-category="Animals" value="Dog">Dog</option>
<option data-category="Animals" value="Cat">Cat</option>
<option data-category="Animals"
value="Elephant">Elephant</option>
</select>
</div>
</div>
</body>
</html>
Write a JS Program to implement Tree Menu. Show the directory
59 structure of the folder where your CSS codes for Semester 5 are saved.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Tree Menu Example</title>
</head>
<body>
<h1>Directory Structure for Semester 5 CSS Codes</h1>

<ul id="treeMenu">
<li><span onclick="toggleVisibility('semester5')">+ Semester
5</span>
<ul id="semester5" style="display:none;">
<li><span onclick="toggleVisibility('cssFolder')">+
CSS</span>
<ul id="cssFolder" style="display:none;">
<li>styles.css</li>
<li>layout.css</li>
<li><span onclick="toggleVisibility('themesFolder')">+
themes</span>
<ul id="themesFolder" style="display:none;">
<li>dark.css</li>
<li>light.css</li>
</ul>
</li>
</ul>
</li>
<li><span onclick="toggleVisibility('imagesFolder')">+
images</span>
<ul id="imagesFolder" style="display:none;">
<li>logo.png</li>
<li>header.png</li>
</ul>
</li>
</ul>
</li>
</ul>

<script>
// Function to toggle visibility of nested folders/files
function toggleVisibility(id) {
const folder = document.getElementById(id);
const icon = event.target; // Get the clicked span element

if (folder.style.display === "none") {


folder.style.display = "block";
icon.textContent = icon.textContent.replace('+', '-'); // Change
'+' to '-'
} else {
folder.style.display = "none";
icon.textContent = icon.textContent.replace('-', '+'); // Change
'-' to '+'
}
}
</script>
</body>
</html>

Write a JS to create a 2 Pulldown menus and according to the selection of


60 element from 1st menu, the list of 2nd Pull Down menu must be updated
dynamically.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Dynamic Dropdown Menus</title>
</head>
<body>
<h1>Dynamic Pulldown Menus</h1>

<label for="firstMenu">Choose a Category:</label>


<select id="firstMenu" onchange="updateSecondMenu()">
<option value="">Select Category</option>
<option value="fruits">Fruits</option>
<option value="vegetables">Vegetables</option>
</select>

<br><br>

<label for="secondMenu">Choose an Item:</label>


<select id="secondMenu">
<option value="">Select Item</option>
</select>

<script>
// Function to update the second dropdown menu based on the first
menu selection
function updateSecondMenu() {
// Get the value of the first dropdown (category selected)
const category = document.getElementById("firstMenu").value;
const secondMenu = document.getElementById("secondMenu");

// Clear the current options in the second menu


secondMenu.innerHTML = "<option value=''>Select
Item</option>";

// Options to be added based on the category selected


let options = [];

if (category === "fruits") {


options = ["Apple", "Banana", "Orange", "Mango"];
} else if (category === "vegetables") {
options = ["Carrot", "Potato", "Broccoli", "Spinach"];
}

// Add the new options to the second dropdown


options.forEach(function(item) {
let option = document.createElement("option");
option.value = item.toLowerCase();
option.textContent = item;
secondMenu.appendChild(option);
});
}
</script>
</body>
</html>

61 Write a javascript program to link banner advertisements to different


URLs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Ad Rotator</title>
</head>
<body>
<a id="link" target="_blank">
<img id="banner" alt="Ad Banner" width="300" height="150">
</a>
<script>
const ads = [
["/ad1", "https://via.placeholder.com/300x150/0df111"],
["/ad2", "https://via.placeholder.com/300x150/f22f0d"],
["/ad3", "https://via.placeholder.com/300x150/0d83f2"]
];
let index = 0;
function rotate() {
document.getElementById("link").href = ads[index][0];
document.getElementById("banner").src = ads[index][1];
index = (index + 1) % ads.length;
}
setInterval(rotate, 2000);
rotate();
</script>
</body>
</html>
Create a slideshow with the group of three images, also simulate next and
62 previous transition between slides in your Java script.

<!DOCTYPE html>
<html>
<head>
<title>Slideshow</title>
<script>
var pics = ['1.jpg', '2.jpg', '3.jpg']; // Corrected array syntax
var count = 0;

function slideshow(status) {
count = count + status;
if (count >= pics.length) { // Corrected 'lenght' to 'length'
count = 0; // Loop back to the first image
}
if (count < 0) {
count = pics.length - 1; // Loop back to the last image
}
document.img1.src = pics[count]; // Update the image source
}
</script>
</head>
<body>
<img src="1.jpg" width="200" name="img1" id="img1">
<br>
<input type="button" value="Next" onclick="slideshow(1)">
<input type="button" value="Back" onclick="slideshow(-1)">
</body>
</html>

63 Write a JavaScript to demonstrate the use of Side bar menu.


<!DOCTYPE html>
<html>
<head>
<style>
.sidebar {
position: fixed; top: 0; left: -150px; width: 150px; height: 100%;
background: #333; color: white; padding: 10px; transition: 0.3s;
}
.sidebar a { color: white; display: block; margin: 10px 0; }
button {
position: fixed; top: 10px; left: 20px; z-index: 1;
background: #333; color: white; border: none; padding: 10px;
}
</style>
</head>
<body>
<button onclick="toggle()">☰</button>
<div id="sidebar" class="sidebar">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
</div>
<script>
function toggle() {
const sidebar = document.getElementById('sidebar');
sidebar.style.left = sidebar.style.left === '0px' ? '-150px' : '0px';
}
</script>
</body>
</html>

Write a JS Program to create a slideshow of minimum 5 images and link


64 them to different websites. Apply rollover action to all images in a way
that when a mouse hover's over an image, the url of the linked website
should appear below the slideshow. The slideshow should be timed and
no buttons should be there on the screen.

You might also like