CSS Summer 24
CSS Summer 24
Math.abs(x): Returns the absolute value of x. This means it always returns a positive value,
regardless of the input sign.
console.log(Math.abs(-5)); // Output: 5
Math.round(x): Rounds x to the nearest integer. If the decimal part is 0.5 or greater, it rounds
up; otherwise, it rounds down.
console.log(Math.round(3.7)); // Output: 4
console.log(Math.round(3.2)); // Output: 3
Math.ceil(x): Returns the smallest integer greater than or equal to x. This always rounds up,
even if the decimal part is very small.
console.log(Math.ceil(3.1)); // Output: 4
Math.floor(x): Returns the largest integer less than or equal to x. This always rounds down,
even if the decimal part is very close to 1.
console.log(Math.floor(3.9)); // Output: 3
c) Write a JavaScript program that will print even numbers from 1 to 20.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Print Even Numbers from 1 to 20</title>
</head>
<body>
<script>
let evenNumbers = [];
// Loop from 1 to 20
for (let i = 1; i <= 20; i++) {
// Check if the number is even
if (i % 2 === 0) {
evenNumbers.push(i); // Add even number to the array
}
}
</body>
</html>
<p id="originalArray"></p>
<p id="ascendingOrder"></p>
<p id="descendingOrder"></p>
<script>
// Define the array
let array = [45, 12, 78, 34, 89, 23, 56];
</body>
</html>
e) Give syntax of and explain function in JavaScript with suitable example.
Ans.In JavaScript, a function is a block of code designed to perform a particular task. Functions
are executed when they are invoked (called), and they can accept parameters (inputs) and return
a value.
Syntax of a Function:
function functionName(parameters) {
// Code to be executed
return value; // Optional return statement
}
b) Explain setter and getter properties in JavaScript with the help of suitable example.
Ans.Property getters and setters
1. The accessor properties. They are essentially functions that work on
getting and setting a value.
2. Accessor properties are represented by “getter†and “setter†methods. In
an object literal they are denoted by get and set.
let obj = {
get propName() {
// getter, the code executed on getting obj.propName
},
set propName(value) {
// setter, the code executed on setting obj.propName = value
}
};
3. An object property is a name, a value and a set of attributes. The value
may be replaced by one or two methods, known as setter and a getter.
4. When program queries the value of an accessor property, Javascript
invoke getter method(passing no arguments). The retuen value of this
method become the value of the property access expression.
5. When program sets the value of an accessor property. Javascript invoke
the setter method, passing the value of right-hand side of assignment. This
method is responsible for setting the property value.
ï‚· If property has both getter and a setter method, it is read/write
property.
ï‚· If property has only a getter method , it is read-only property.
ï‚· If property has only a setter method , it is a write-only property.
6. getter works when obj.propName is read, the setter – when it is assigned.
Example:
<html>
<head>
<title>Functions</title>
<body>
<script language="Javascript">
var myCar = {
/* Data properties */
defColor: "blue",
defMake: "Toyota",
<p id="result"></p>
<script>
// JavaScript to check if a number is positive, negative, or zero using switch
function checkNumber() {
let num = parseFloat(document.getElementById("numberInput").value);
let resultText = document.getElementById("result");
switch (true) {
case (num > 0):
resultText.textContent = num + " is a positive number.";
resultText.className = "positive"; // Add class for styling
break;
case (num < 0):
resultText.textContent = num + " is a negative number.";
resultText.className = "negative"; // Add class for styling
break;
case (num === 0):
resultText.textContent = "The number is zero.";
resultText.className = "zero"; // Add class for styling
break;
default:
resultText.textContent = "Please enter a valid number.";
resultText.className = ""; // Remove any existing class
}
}
</script>
</body>
</html>
d) State the use of following methods:
i) charCodeAt()
ii) fromCharCode ()
Ans.i) charCodeAt():
The charCodeAt() method in JavaScript is used to return the Unicode value (also known as the
character code) of the character at a specified index in a string.
Syntax:
string.charCodeAt(index)
Example:
let str = "Hello";
let charCode = str.charCodeAt(1); // Index 1 corresponds to 'e'
console.log(charCode); // Output: 101 (Unicode for 'e')
ii) fromCharCode():
The fromCharCode() method is a static method of the String object that creates a string from the
given sequence of Unicode values. It takes one or more Unicode values as arguments and returns
the corresponding characters.
Syntax:
String.fromCharCode(num1, num2, ..., numN)
Example:
let str = String.fromCharCode(72, 101, 108, 108, 111); // Unicode for 'H', 'e', 'l', 'l', 'o'
console.log(str); // Output: "Hello"
b) Write a JavaScript function that checks whether a passed string is palindrome or not.
Ans.A palindrome is a string that reads the same backward as forward (e.g., "madam",
"racecar"). To check if a string is a palindrome in JavaScript, we can write a function that
compares the original string with its reversed version.
function isPalindrome(str) {
// Remove non-alphanumeric characters and convert the string to lowercase
let cleanedStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
// Example Usage:
console.log(isPalindrome("madam")); // Output: true
console.log(isPalindrome("racecar")); // Output: true
console.log(isPalindrome("hello")); // Output: false
console.log(isPalindrome("A man, a plan, a canal: Panama")); // Output: true
c) Explain how to add and sort elements in array with suitable example.
Ans.In JavaScript, you can add elements to an array using methods like push(), unshift(), or
directly by assigning values to specific indexes. You can also sort the array using the sort()
method. Here's an explanation of how to add elements and sort arrays with examples.
1. Adding Elements to an Array
a) Using push():
The push() method adds one or more elements to the end of the array.
b) Using unshift():
The unshift() method adds one or more elements to the beginning of the array.
c) Direct Assignment:
You can also add elements to an array by assigning values to specific indexes, even if they don't
exist yet.
2. Sorting an Array
The sort() method sorts the elements of an array in place and returns the sorted array. By default,
it sorts elements as strings in alphabetical and ascending order. For numeric or customized
sorting, a compare function must be provided.
a) Sorting an Array of Strings:
By default, sort() sorts strings alphabetically.
b) Sorting an Array of Numbers:
By default, sort() sorts numbers lexicographically (as strings), which can lead to incorrect results.
To sort numbers correctly, you need to provide a compare function.
c) Sorting in Descending Order:
To sort an array in descending order, you can modify the compare function.
d) Sorting Arrays of Objects:
You can sort arrays of objects by using a custom compare function. For example, sorting an
array of objects by a specific property like age.
a) State what is frame? Explain how it can be created with suitable example.
Ans.
b) Explain the steps to create floating menu and chain select menu
Ans.
</body>
</html>
d) Write a JavaScript function to check whether a given address is a valid IP address or
not.
Ans.
function isValidIP(ip) {
// Regular expression to check if the string is a valid IPv4 address
const ipPattern = /^(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]?)$/;
<script>
// JavaScript to simulate progress and update the status bar
function startProgress() {
var statusBar = document.getElementById("statusBar");
var width = 0;
var interval = setInterval(function() {
if (width >= 100) {
clearInterval(interval); // Stop when the progress reaches 100%
statusBar.innerHTML = "Completed";
} else {
width++; // Increase the width
statusBar.style.width = width + '%'; // Update the width of the bar
statusBar.innerHTML = width + '%'; // Update the displayed percentage
}
}, 100); // Interval for updating the progress (100 ms for each step)
}
</script>
</body>
</html>
a) Write HTML script that displays textboxes for accepting username and password. Write
proper JavaScript such that when the user clicks on submit button
i) All textboxes must get disabled and change the color to 'RED' and with respective labels.
ii) Prompt the error message if the password is less than six characters.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Username and Password Form</title>
<style>
/* Styling the form elements */
label {
display: inline-block;
width: 100px;
}
input[type="text"], input[type="password"] {
margin-bottom: 10px;
}
.red {
color: red;
}
</style>
</head>
<body>
<form id="loginForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username" placeholder="Enter username"
required><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="Enter password"
required><br>
<script>
function handleSubmit() {
// Get the form elements
const usernameInput = document.getElementById("username");
const passwordInput = document.getElementById("password");
usernameLabel.classList.add("red");
passwordLabel.classList.add("red");
}
</script>
</body>
</html>
b) Write a webpage that displays a form that contains an input for students rollno and
names user is prompted to enter the input student rollno and name and rollno becomes
value of the cookie.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Form</title>
<script>
function setCookie(name, value, days) {
const expires = new Date(Date.now() + days * 864e5).toUTCString();
document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires +
'; path=/';
}
function handleSubmit(event) {
event.preventDefault();
const rollno = document.getElementById('rollno').value;
const name = document.getElementById('name').value;
c) Write a JavaScript to create rollover effect that involves text and images. When the user
places his or her mouse pointer over a book title, the corresponding book image appears.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Book Rollover Effect</title>
<style>
body {
font-family: Arial, sans-serif;
}
.book-title {
cursor: pointer;
color: blue;
text-decoration: underline;
margin: 10px 0;
}
.book-image {
display: none; /* Hide images by default */
margin-top: 10px;
max-width: 200px; /* Set a max width for the images */
}
</style>
</head>
<body>
<h1>Book Rollover Effect</h1>
<div>
<div class="book-title" onmouseover="showImage('book1')"
onmouseout="hideImage('book1')">Book Title 1</div>
<img id="book1" class="book-image" src="https://via.placeholder.com/200?text=Book+1"
alt="Book Title 1">
<script>
function showImage(bookId) {
const image = document.getElementById(bookId);
image.style.display = 'block'; // Show the image
}
function hideImage(bookId) {
const image = document.getElementById(bookId);
image.style.display = 'none'; // Hide the image
}
</script>
</body>
</html>
a) Explain following form control/elements with example Button, Text, TextArea, Select
Checkbox, Form.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sample Form</title>
</head>
<body>
<h1>User Feedback Form</h1>
b) Write a JavaScript for protecting web page by implementing the following steps:
i) Hiding your source code
ii) Disabling the right MouseButton
iii) Hiding JavaScript
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Protected Web Page</title>
<script>
// Step 1: Disable right-click (context menu)
document.addEventListener('contextmenu', function (e) {
e.preventDefault(); // Prevent right-click menu from opening
alert('Right-click is disabled on this webpage.');
});
// Step 2: Disable keyboard shortcuts that are commonly used to inspect or view the source
code
document.addEventListener('keydown', function (e) {
// Disable F12 (Developer Tools), Ctrl+Shift+I, Ctrl+Shift+J, and Ctrl+U (View Source)
if (e.key === 'F12' ||
(e.ctrlKey && e.shiftKey && (e.key === 'I' || e.key === 'J')) ||
(e.ctrlKey && e.key === 'U')) {
e.preventDefault(); // Prevent these shortcuts from working
alert('Inspecting the page is disabled.');
}
});
<style>
/* Additional CSS for disabling text selection */
body {
user-select: none; /* Prevent users from selecting and copying text */
}
</style>
</head>
<body>
</body>
</html>