IMPORTANT JS PROGRAMS FOR PRACTICAL
Q1.Write a JavaScript function to check
whether a given value is an IP address or not.
SOLUTION:
function
isIPAddress(value) {
// Split the value into parts based on the
'.' for IPv4 or ':' for IPv6
const parts = value.split(value.includes('.')
? '.' : ':');
// Check if there are the correct number of
parts for IPv4 (4) or IPv6 (8)
if (parts.length === (value.includes('.') ? 4
: 8)) {
// Check if each part is a valid number in
the appropriate range
if (parts.every(part => {
const number = parseInt(part, 16);
return !isNaN(number) && number
>= 0 && number <= 255;
})) {
return true; // It's a valid IP address
}
}
return false; // It's not a valid IP address
}
//
Example usage:
console.log(isIPAddress("192.168.1.1"));
// true
console.log(isIPAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334"));
// true
console.log(isIPAddress("notanipaddress"));
// false
Q2. Design patient admission form for
hospital having fields like patient ID, patient name,
address, city, contact number, date of
birth and admission date. Do the validations as
mentioned below using JavaScript:
o All are required fields
o Length of ID should be more than 5
o Name should not have digits
o Contact number should not have alphabets
o Date of admission should be greater than
date of birth
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>Patient Admission
Form</title>
<script>
function validateForm() {
// Get form input values
const patientId =
document.getElementById('patientId').value;
const patientName =
document.getElementById('patientName').value;
const address =
document.getElementById('address').value;
const city =
document.getElementById('city').value;
const contactNumber =
document.getElementById('contactNumber').value;
const dateOfBirth = new
Date(document.getElementById('dateOfBirth').value);
const admissionDate = new
Date(document.getElementById('admissionDate').value);
// Check if all fields are filled
if (!patientId || !patientName ||
!address || !city || !contactNumber || !dateOfBirth || !admissionDate) {
alert("All fields are
required.");
return false;
}
// Check patient ID length
if (patientId.length <= 5) {
alert("Patient ID should be more
than 5 characters.");
return false;
}
// Check if patient name contains digits
if (/\d/.test(patientName)) {
alert("Patient name should not
have digits.");
return false;
}
// Check if contact number contains
alphabets
if (/[a-zA-Z]/.test(contactNumber)) {
alert("Contact number should not
have alphabets.");
return false;
}
// Check if admission date is greater
than date of birth
if (admissionDate <= dateOfBirth) {
alert("Admission date should be
greater than date of birth.");
return false;
}
return true;
}
</script>
</head>
<body>
<h1>Patient Admission Form</h1>
<form onsubmit="return
validateForm()">
<label
for="patientId">Patient ID:</label>
<input type="text"
id="patientId" name="patientId" required><br>
<label
for="patientName">Patient Name:</label>
<input type="text"
id="patientName" name="patientName" required><br>
<label
for="address">Address:</label>
<input type="text"
id="address" name="address" required><br>
<label
for="city">City:</label>
<input type="text"
id="city" name="city" required><br>
<label
for="contactNumber">Contact Number:</label>
<input type="text"
id="contactNumber" name="contactNumber"
required><br>
<label
for="dateOfBirth">Date of Birth:</label>
<input type="date"
id="dateOfBirth" name="dateOfBirth" required><br>
<label
for="admissionDate">Admission Date:</label>
<input type="date"
id="admissionDate" name="admissionDate"
required><br>
<input type="submit"
value="Submit">
</form>
</body>
</html>
Q3.Design login form using HTML and write
JavaScript validation code :
o Username should not be blank and greater
than 15 characters
o Password should be minimum 8 characters
and maximum 15 characters
and should contain alphabets and digits
only.
o Confirm password must be similar to
password.
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>Login Form</title>
<script>
function validateForm() {
const username =
document.getElementById('username').value;
const password =
document.getElementById('password').value;
const confirmPassword =
document.getElementById('confirmPassword').value;
// Check if the username is not blank and
greater than 15 characters
if (username.trim() === '' ||
username.length > 15) {
alert("Username should not be
blank and greater than 15 characters.");
return false;
}
// Check if the password is between 8 and
15 characters and contains only alphabets and digits
if
(!/^[a-zA-Z0-9]{8,15}$/.test(password)) {
alert("Password should be 8 to 15
characters and contain only alphabets and digits.");
return false;
}
// Check if the confirm password matches
the password
if (password !== confirmPassword) {
alert("Confirm password must be
similar to the password.");
return false;
}
return true;
}
</script>
</head>
<body>
<h1>Login Form</h1>
<form onsubmit="return
validateForm()">
<label
for="username">Username:</label>
<input type="text"
id="username" name="username" required><br>
<label
for="password">Password:</label>
<input type="password"
id="password" name="password" required><br>
<label
for="confirmPassword">Confirm Password:</label>
<input type="password"
id="confirmPassword" name="confirmPassword"
required><br>
<input type="submit"
value="Login">
</form>
</body>
</html>
Q4.Write a program to display user location
(longitude and latitude) inside <h3> tag. Also write JavaScript program
to greet the user (Good Morning, Good Afternoon, Good Evening and Good Night)
according to time.
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>User Location and
Greeting</title>
<script>
// Get user's location and display it in an
<h3> tag
function getUserLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
const latitude =
position.coords.latitude;
const longitude =
position.coords.longitude;
const locationH3 =
document.getElementById('location');
locationH3.textContent = `Your
location: Latitude ${latitude}, Longitude ${longitude}`;
});
} else {
alert("Geolocation is not
supported by your browser.");
}
}
// Determine the time of day and greet the
user accordingly
function greetUser() {
const currentDate = new Date();
const currentHour =
currentDate.getHours();
const greetingH3 =
document.getElementById('greeting');
if (currentHour >= 5 &&
currentHour < 12) {
greetingH3.textContent = "Good
Morning";
} else if (currentHour >= 12
&& currentHour < 17) {
greetingH3.textContent = "Good
Afternoon";
} else if (currentHour >= 17
&& currentHour < 21) {
greetingH3.textContent = "Good
Evening";
} else {
greetingH3.textContent = "Good
Night";
}
}
// Call the functions when the page loads
window.onload = function() {
getUserLocation();
greetUser();
};
</script>
</head>
<body>
<h1>User Location and
Greeting</h1>
<h3 id="location">Fetching
your location...</h3>
<h3 id="greeting">Determining
the time of day...</h3>
</body>
</html>
Q5.Write a program using HTML and
JavaScript to implement calculator having +, -, *, /, %, Square root,
power(x,y) operations. Accept the input from user and accordingly show the
result of selected operation.
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>Calculator</title>
<script>
function calculate() {
const num1 =
parseFloat(document.getElementById('num1').value);
const num2 =
parseFloat(document.getElementById('num2').value);
const operator =
document.getElementById('operator').value;
let result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 !== 0) {
result = num1 / num2;
} else {
alert("Division by zero is not
allowed.");
return;
}
break;
case '%':
result = num1 % num2;
break;
case 'sqrt':
result = Math.sqrt(num1);
break;
case 'power':
result = Math.pow(num1, num2);
break;
default:
alert("Invalid operator.");
return;
}
document.getElementById('result').textContent = `Result: ${result}`;
}
</script>
</head>
<body>
<h1>Calculator</h1>
<label for="num1">Number
1:</label>
<input type="number"
id="num1" required><br>
<label
for="operator">Operation:</label>
<select id="operator"
required>
<option
value="+">+</option>
<option
value="-">-</option>
<option
value="*">*</option>
<option
value="/">/</option>
<option
value="%">%</option>
<option value="sqrt">Square
Root</option>
<option
value="power">Power</option>
</select><br>
<label for="num2">Number
2:</label>
<input type="number"
id="num2" required><br>
<button
onclick="calculate()">Calculate</button>
<p id="result"></p>
</body>
</html>
Q6.Write a Javascript program to create a
class called Person with a name and age attribute. Create three instances of
the Person class, set their attributes using the constructor, and print their
name and age. Also display name of the eldest person.
SOLUTION:
class
Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
//
Create three instances of the Person class
const
person1 = new Person("Alice", 30);
const
person2 = new Person("Bob", 25);
const
person3 = new Person("Charlie", 35);
//
Print the name and age of each person
console.log("Person
1: Name =", person1.name, "Age =", person1.age);
console.log("Person
2: Name =", person2.name, "Age =", person2.age);
console.log("Person
3: Name =", person3.name, "Age =", person3.age);
//
Find the eldest person
let
eldest = person1;
if
(person2.age > eldest.age) {
eldest = person2;
}
if
(person3.age > eldest.age) {
eldest = person3;
}
console.log("The
eldest person is", eldest.name, "with an age of", eldest.age);
Q7.Write a Javascript program to create a
class called Car with attributes model_name, price, and
type. Create three instances of the Car
class, set their attributes using the constructor, and print
the details of cheapest car.
SOLUTION:
class
Car {
constructor(model_name, price, type) {
this.model_name = model_name;
this.price = price;
this.type = type;
}
}
//
Create three instances of the Car class
const
car1 = new Car("Model A", 30000, "Sedan");
const
car2 = new Car("Model B", 25000, "SUV");
const
car3 = new Car("Model C", 35000, "Convertible");
//
Print the details of each car
console.log("Car
1: Model =", car1.model_name, "Price =", car1.price, "Type
=", car1.type);
console.log("Car
2: Model =", car2.model_name, "Price =", car2.price, "Type
=", car2.type);
console.log("Car
3: Model =", car3.model_name, "Price =", car3.price, "Type
=", car3.type);
//
Find the cheapest car
let
cheapestCar = car1;
if
(car2.price < cheapestCar.price) {
cheapestCar = car2;
}
if
(car3.price < cheapestCar.price) {
cheapestCar = car3;
}
console.log("The
details of the cheapest car: Model =", cheapestCar.model_name, "Price
=", cheapestCar.price, "Type =", cheapestCar.type);
Q8.Write a program using HTML and
Javascript to display smiley face, half circle, polygon and filled rectangle.
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>Shapes and Smiley
Face</title>
<style>
#canvas {
width: 400px;
height: 400px;
border: 1px solid black;
}
</style>
</head>
<body>
<h1>Shapes and Smiley Face</h1>
<canvas
id="canvas"></canvas>
<script>
const canvas =
document.getElementById('canvas');
const context = canvas.getContext('2d');
// Draw a smiley face
context.beginPath();
context.arc(200, 200, 100, 0, Math.PI * 2);
// Head
context.moveTo(160, 160);
context.arc(140, 160, 20, 0, Math.PI); //
Left eye
context.moveTo(260, 160);
context.arc(240, 160, 20, 0, Math.PI); //
Right eye
context.moveTo(200, 200);
context.arc(200, 200, 60, 0, Math.PI,
false); // Mouth
context.stroke();
// Draw a half circle
context.beginPath();
context.arc(100, 320, 80, 0, Math.PI,
false);
context.stroke();
// Draw a polygon (triangle)
context.beginPath();
context.moveTo(320, 320);
context.lineTo(360, 400);
context.lineTo(280, 400);
context.closePath();
context.stroke();
// Draw a filled rectangle
context.fillStyle = "blue";
context.fillRect(100, 100, 80, 50);
</script>
</body>
</html>
Q9.Write a program using canvas to display
50 random circles. Every circle is having same size and different color.
Circles are displayed randomly.
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>Random Circles</title>
<style>
#canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>Random Circles</h1>
<canvas
id="canvas"></canvas>
<script>
const canvas =
document.getElementById('canvas');
const context = canvas.getContext('2d');
const numberOfCircles = 50;
canvas.width = 600; // Set the canvas width
canvas.height = 400; // Set the canvas
height
// Function to generate a random color
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color +=
letters[Math.floor(Math.random() * 16)];
}
return color;
}
// Draw 50 random circles with different
colors
for (let i = 0; i < numberOfCircles;
i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
const radius = 20; // You can adjust the
size of the circles here
const color = getRandomColor();
context.beginPath();
context.arc(x, y, radius, 0, Math.PI *
2);
context.fillStyle = color;
context.fill();
context.closePath();
}
</script>
</body>
</html>
Q10.Create a form with text box and two
radio buttons with value Prime Number and Perfect Number. If Prime Number radio
button is selected then display if the number in text box is a prime number or
not on the click of button. If Perfect Number radio button is selected then
display if the number in text box is a perfect number or not on the click of
button.
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>Prime and Perfect Number
Checker</title>
<script>
function isPrimeNumber(number) {
if (number <= 1) {
return false;
}
for (let i = 2; i <=
Math.sqrt(number); i++) {
if (number % i === 0) {
return false;
}
}
return true;
}
function isPerfectNumber(number) {
let sum = 1;
for (let i = 2; i * i <= number; i++)
{
if (number % i === 0) {
sum += i;
if (i !== number / i) {
sum += number / i;
}
}
}
return sum === number;
}
function checkNumber() {
const number =
parseInt(document.getElementById('number').value);
const resultDiv =
document.getElementById('result');
const primeRadio =
document.getElementById('primeRadio');
if (primeRadio.checked) {
if (isPrimeNumber(number)) {
resultDiv.textContent = `${number} is
a Prime Number.`;
} else {
resultDiv.textContent = `${number} is
not a Prime Number.`;
}
} else {
if (isPerfectNumber(number)) {
resultDiv.textContent = `${number} is
a Perfect Number.`;
} else {
resultDiv.textContent = `${number} is
not a Perfect Number.`;
}
}
}
</script>
</head>
<body>
<h1>Prime and Perfect Number
Checker</h1>
<form>
<label for="number">Enter a
number:</label>
<input type="number"
id="number" required>
<br>
<label>Select a number
type:</label>
<input type="radio"
id="primeRadio" name="numberType" value="Prime
Number" checked>
<label
for="primeRadio">Prime Number</label>
<input type="radio"
id="perfectRadio" name="numberType" value="Perfect
Number">
<label
for="perfectRadio">Perfect Number</label>
<br>
<button type="button"
onclick="checkNumber()">Check Number</button>
</form>
<div id="result"></div>
</body>
</html>
Q11.Write a program to implement calculator
using HTML and JavaScript. Calculator should have following operations : Square
Root, Power, Log, Floor, Ceil.
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>Calculator</title>
<style>
#calculator {
width: 300px;
margin: 0 auto;
border: 1px solid #ccc;
padding: 10px;
}
</style>
</head>
<body>
<h1>Calculator</h1>
<div id="calculator">
<label for="number">Enter a
number:</label>
<input type="number"
id="number">
<br>
<label>Select an
operation:</label>
<select id="operation">
<option
value="sqrt">Square Root</option>
<option
value="power">Power</option>
<option
value="log">Log</option>
<option
value="floor">Floor</option>
<option
value="ceil">Ceil</option>
</select>
<br>
<button
onclick="calculate()">Calculate</button>
<br>
<p id="result"></p>
</div>
<script>
function calculate() {
const number =
parseFloat(document.getElementById('number').value);
const operation =
document.getElementById('operation').value;
const resultDiv =
document.getElementById('result');
let result;
switch (operation) {
case 'sqrt':
result = Math.sqrt(number);
break;
case 'power':
result = Math.pow(number, 2);
break;
case 'log':
result = Math.log(number);
break;
case 'floor':
result = Math.floor(number);
break;
case 'ceil':
result = Math.ceil(number);
break;
default:
result = 'Invalid operation';
break;
}
resultDiv.textContent = `Result:
${result}`;
}
</script>
</body>
</html>
Q12.Write a program to accept date of birth
using calendar and display age of the person in years and months. Future dates
should not be selected.
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>Age Calculator</title>
</head>
<body>
<h1>Age Calculator</h1>
<label for="dob">Select your
Date of Birth:</label>
<input type="date"
id="dob" max="<?php echo date('Y-m-d'); ?>"
required>
<button
onclick="calculateAge()">Calculate Age</button>
<p id="ageResult"></p>
<script>
function calculateAge() {
const dobInput =
document.getElementById('dob');
const ageResult =
document.getElementById('ageResult');
const selectedDate = new
Date(dobInput.value);
const currentDate = new Date();
if (selectedDate > currentDate) {
ageResult.textContent = "Invalid
date of birth. Please select a date in the past.";
} else {
const years = currentDate.getFullYear()
- selectedDate.getFullYear();
const currentMonth =
currentDate.getMonth();
const selectedMonth =
selectedDate.getMonth();
let months = currentMonth -
selectedMonth;
if (months < 0) {
years--;
months += 12;
}
ageResult.textContent = `Your age is
${years} years and ${months} months.`;
}
}
</script>
</body>
</html>
Q13.Create a web page with a button and a
text input field. Validate the text. Text should have atleast one alphabet, one
digit and # symbol. If the text is valid then store the text entered by the
user in the input field into localStorage when the button is clicked. Create a
separate button that retrieves and displays the stored data from localStorage.
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>Local Storage
Example</title>
</head>
<body>
<h1>Local Storage Example</h1>
<label for="text">Enter text
(with at least one alphabet, one digit, and # symbol):</label>
<input type="text"
id="text">
<button
onclick="validateText()">Validate Text</button>
<button
onclick="storeText()">Store Text</button>
<button
onclick="retrieveText()">Retrieve Text</button>
<div id="result"></div>
<script>
function validateText() {
const textInput =
document.getElementById('text');
const text = textInput.value;
// Regular expression to check if the
text contains at least one alphabet, one digit, and #
const regex =
/^(?=.*[a-zA-Z])(?=.*\d)(?=.*#).+$/;
if (regex.test(text)) {
document.getElementById('result').textContent = 'Text is valid.';
} else {
document.getElementById('result').textContent = 'Text is not valid.
Please follow the criteria.';
}
}
function storeText() {
const textInput =
document.getElementById('text');
const text = textInput.value;
// Check if the text is valid before
storing
const regex =
/^(?=.*[a-zA-Z])(?=.*\d)(?=.*#).+$/;
if (regex.test(text)) {
localStorage.setItem('userText', text);
textInput.value = '';
document.getElementById('result').textContent = 'Text has been stored in
local storage.';
} else {
document.getElementById('result').textContent = 'Text is not valid.
Please follow the criteria.';
}
}
function retrieveText() {
const storedText =
localStorage.getItem('userText');
if (storedText) {
document.getElementById('result').textContent = 'Stored Text: ' +
storedText;
} else {
document.getElementById('result').textContent = 'No text has been stored
in local storage.';
}
}
</script>
</body>
</html>
14.Write a JavaScript program to display 1)
No. of words in the string 2) Display array of numbers in descending order.
SOLUTION:
//
Function to count the number of words in a string
function
countWords(inputString) {
// Use a regular expression to split the
string into words
const words = inputString.split(/\s+/);
return words.length;
}
//
Function to sort an array of numbers in descending order
function
sortDescending(numbers) {
return numbers.sort((a, b) => b - a);
}
//
Example string
const
text = "This is a sample string with multiple words";
//
Count the number of words in the string
const
wordCount = countWords(text);
//
Example array of numbers
const
numbers = [5, 1, 8, 3, 2, 9, 6];
//
Sort the array of numbers in descending order
const
sortedNumbers = sortDescending(numbers);
//
Display the results
console.log("Number
of words in the string:", wordCount);
console.log("Array
of numbers in descending order:", sortedNumbers);
Q15.Create an object to represent a
student. The object should have properties for the student's name, ID number,
major, and GPA. Access and print the values of the student's name and ID number
properties. Add a property to the student object for the
student's email address. Create a function
to check if a student is eligible for a scholarship. The function should take
the student's GPA as input and return true if the GPA is above 3.5 and false
otherwise. Check if the student is eligible for a scholarship and print the
result.
SOLUTION:
//
Create a student object
const
student = {
name: "John Doe",
ID: "123456",
major: "Computer Science",
GPA: 3.7,
};
//
Access and print the values of name and ID properties
console.log("Student
Name: " + student.name);
console.log("Student
ID: " + student.ID);
//
Add a property for the student's email address
student.email
= "john.doe@example.com";
//
Function to check scholarship eligibility
function
isEligibleForScholarship(GPA) {
return GPA > 3.5;
}
//
Check if the student is eligible for a scholarship
const
eligibleForScholarship = isEligibleForScholarship(student.GPA);
if
(eligibleForScholarship) {
console.log("Student is eligible for a
scholarship.");
}
else {
console.log("Student is not eligible for
a scholarship.");
}
Q16.Create a form with text box and two
radio buttons with value Prime Number and Perfect Number. If Prime Number radio
button is selected then display if the number in text box is a prime number or
not on the click of button. If Perfect Number radio button is selected then
display if the number in text box is a perfect number or not on the click of
button.
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>Number Checker</title>
<script>
function isPrimeNumber(number) {
if (number <= 1) {
return false;
}
for (let i = 2; i <=
Math.sqrt(number); i++) {
if (number % i === 0) {
return false;
}
}
return true;
}
function isPerfectNumber(number) {
let sum = 1;
for (let i = 2; i * i <= number; i++)
{
if (number % i === 0) {
sum += i;
if (i !== number / i) {
sum += number / i;
}
}
}
return sum === number;
}
function checkNumber() {
const number =
parseInt(document.getElementById('number').value);
const resultDiv =
document.getElementById('result');
const primeRadio =
document.getElementById('primeRadio');
if (primeRadio.checked) {
if (isPrimeNumber(number)) {
resultDiv.textContent = `${number} is
a Prime Number.`;
} else {
resultDiv.textContent = `${number} is
not a Prime Number.`;
}
} else {
if (isPerfectNumber(number)) {
resultDiv.textContent = `${number} is
a Perfect Number.`;
} else {
resultDiv.textContent = `${number} is
not a Perfect Number.`;
}
}
}
</script>
</head>
<body>
<h1>Number Checker</h1>
<form>
<label for="number">Enter a
number:</label>
<input type="number"
id="number" required>
<br>
<label>Select a number
type:</label>
<input type="radio"
id="primeRadio" name="numberType" value="Prime
Number" checked>
<label
for="primeRadio">Prime Number</label>
<input type="radio"
id="perfectRadio" name="numberType" value="Perfect
Number">
<label
for="perfectRadio">Perfect Number</label>
<br>
<button type="button"
onclick="checkNumber()">Check Number</button>
</form>
<div id="result"></div>
</body>
</html>
Q17.Write a program to implement calculator
using HTML and JavaScript. Calculator should have following operations : Square
Root, Power, Log, Floor, Ceil.
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>Calculator</title>
<style>
#calculator {
width: 300px;
margin: 0 auto;
border: 1px solid #ccc;
padding: 10px;
}
</style>
</head>
<body>
<h1>Calculator</h1>
<div id="calculator">
<label for="number">Enter a
number:</label>
<input type="number"
id="number" required>
<br>
<label>Select an
operation:</label>
<select id="operation">
<option
value="sqrt">Square Root</option>
<option
value="power">Power</option>
<option
value="log">Log</option>
<option
value="floor">Floor</option>
<option
value="ceil">Ceil</option>
</select>
<br>
<button
onclick="calculate()">Calculate</button>
<br>
<p id="result"></p>
</div>
<script>
function calculate() {
const number =
parseFloat(document.getElementById('number').value);
const operation =
document.getElementById('operation').value;
const resultDiv =
document.getElementById('result');
let result;
switch (operation) {
case 'sqrt':
result = Math.sqrt(number);
break;
case 'power':
result = Math.pow(number, 2);
break;
case 'log':
if (number > 0) {
result = Math.log(number);
} else {
result = "Invalid input for
logarithm.";
}
break;
case 'floor':
result = Math.floor(number);
break;
case 'ceil':
result = Math.ceil(number);
break;
default:
result = 'Invalid operation';
break;
}
resultDiv.textContent = `Result:
${result}`;
}
</script>
</body>
</html>
Q18.Write a program to accept date of birth
using calendar and display age of the person in years and months. Future dates
should not be selected.
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>Age Calculator</title>
<style>
#ageCalculator {
width: 300px;
margin: 0 auto;
border: 1px solid #ccc;
padding: 10px;
}
</style>
</head>
<body>
<h1>Age Calculator</h1>
<div id="ageCalculator">
<label for="dob">Select
your Date of Birth:</label>
<input type="date"
id="dob" max="<?php echo date('Y-m-d'); ?>"
required>
<br>
<button
onclick="calculateAge()">Calculate Age</button>
<br>
<p
id="ageResult"></p>
</div>
<script>
function calculateAge() {
const dobInput =
document.getElementById('dob');
const ageResult =
document.getElementById('ageResult');
const selectedDate = new
Date(dobInput.value);
const currentDate = new Date();
if (selectedDate > currentDate) {
ageResult.textContent = "Invalid
date of birth. Please select a date in the past.";
} else {
const years = currentDate.getFullYear()
- selectedDate.getFullYear();
const currentMonth =
currentDate.getMonth();
const selectedMonth =
selectedDate.getMonth();
let months = currentMonth -
selectedMonth;
if (months < 0) {
years--;
months += 12;
}
ageResult.textContent = `Your age is
${years} years and ${months} months.`;
}
}
</script>
</body>
</html>
Q19.Write a program to display ‘n’ circles
having radius ‘r’ randomly on web page. (Get the value of n and r from user).
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>Random Circles</title>
<style>
.circle {
position: absolute;
background-color: blue;
border-radius: 50%;
}
</style>
</head>
<body>
<h1>Random Circles</h1>
<label for="radius">Enter the
radius of circles (r):</label>
<input type="number"
id="radius" required>
<br>
<label for="count">Enter the
number of circles (n):</label>
<input type="number"
id="count" required>
<br>
<button
onclick="createCircles()">Create Circles</button>
<script>
function createCircles() {
const radius =
parseFloat(document.getElementById('radius').value);
const count =
parseInt(document.getElementById('count').value);
for (let i = 0; i < count; i++) {
const circle =
document.createElement('div');
circle.className = 'circle';
circle.style.width = 2 * radius + 'px';
circle.style.height = 2 * radius +
'px';
circle.style.left = Math.random() *
(window.innerWidth - 2 * radius) + 'px';
circle.style.top = Math.random() *
(window.innerHeight - 2 * radius) + 'px';
document.body.appendChild(circle);
}
}
</script>
</body>
</html>
Q20.Write a program to select a number from
drop-down list and display an image on web page for those many times.
SOLUTION:
<!DOCTYPE
html>
<html>
<head>
<title>Image Repeater</title>
</head>
<body>
<h1>Image Repeater</h1>
<label
for="imageCount">Select the number of times to display the
image:</label>
<select id="imageCount">
<option
value="1">1</option>
<option
value="2">2</option>
<option
value="3">3</option>
<option
value="4">4</option>
<option
value="5">5</option>
</select>
<button
onclick="displayImages()">Display Images</button>
<div
id="imageContainer"></div>
<script>
function displayImages() {
const imageCount =
parseInt(document.getElementById('imageCount').value);
const imageContainer =
document.getElementById('imageContainer');
imageContainer.innerHTML = ''; // Clear
any previous images
for (let i = 0; i < imageCount; i++) {
const image =
document.createElement('img');
image.src = 'your_image_url.jpg'; //
Replace with the URL of the image you want to display
image.alt = 'Image';
imageContainer.appendChild(image);
}
}
</script>
</body>
</html>
Q21.Create an HTML file with a basic
structure, including a simple element (e.g., a div) on the page. Use CSS to
animate the element to move from one side of the screen to another
when a button is clicked.
Create a new HTML file with multiple
elements on the page. Define a keyframe animation that changes the color and
size of these elements over time. Apply the keyframe animation to the elements
using the animation property.
SOLUTION:
1.Moving Element
Across the Screen:
<!DOCTYPE html>
<html>
<head>
<title>Element Animation</title>
<style>
#box {
width: 50px;
height: 50px;
background-color: blue;
position: absolute;
transition: transform 2s;
}
</style>
</head>
<body>
<h1>Element Animation</h1>
<div id="box"></div>
<button
onclick="moveElement()">Move Element</button>
<script>
function moveElement() {
const box =
document.getElementById('box');
box.style.transform =
'translateX(200px)';
}
</script>
</body>
</html>
2.Keyframe Animation
for Changing Color and Size:
<!DOCTYPE
html>
<html>
<head>
<title>Keyframe Animation</title>
<style>
.animated-element {
width: 100px;
height: 100px;
background-color: red;
animation: changeElement 3s infinite;
margin: 10px;
}
@keyframes changeElement {
0% {
background-color: red;
transform: scale(1);
}
50% {
background-color: green;
transform: scale(1.2);
}
100% {
background-color: blue;
transform: scale(0.8);
}
}
</style>
</head>
<body>
<h1>Keyframe Animation</h1>
<div
class="animated-element"></div>
<div
class="animated-element"></div>
<div
class="animated-element"></div>
</body>
</html>
0 Comments