CSS Practical Answers
CSS Practical Answers
Practical 1
Ans.
<html>
<body>
<script language="javascript" type="text/javascript">1
function calculate() {
// Get input values
var num1 = parseFloat(document.getElementById('num1').value);
var num2 = parseFloat(document.getElementById('num2').value);
var operation = document.getElementById('operation').value;
var result = 0;
<button onclick="calculate()">Evaluate</button>
<p id="result"></p>
<p id="message"></p>
</body>
</html>
Output: -
1. Numbers: JavaScript uses a single type for all numbers, whether they
are integers or floating-point numbers.
2. Strings: A sequence of characters used to represent text, enclosed in
single quotes, double quotes, or backticks for template literals.
3. Booleans: Represents logical values that can only be either true or
false.
4. Null: A special value representing the intentional absence of any
object value.
5. Undefined: A value automatically assigned to variables that have
been declared but not initialized or to missing properties of an object.
6. Objects: A collection of properties, where each property is a key-value
pair. Objects can represent more complex data types, such as arrays,
functions, or even other objects.
Practical 2
Ans. <html>
<head>
<style>
table {
width: 200px;
border-collapse: collapse;
margin-top: 20px;
}
table,
th,
td {
border: 1px solid black;
}
th,
td {
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>Number</th>
<th>Square</th>
<th>Cube</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<script language="javascript" type="text/javascript">
function createTable() {
let tableBody = document.getElementById('tableBody');
for (let i = 1; i <= 10; i++) {
let row = document.createElement('tr');
row.innerHTML = `<td>${i}</td><td>${i * i}</td><td>${i * i *
i}</td>`;
tableBody.appendChild(row);
}
}
createTable();
</script>
</body>
</html>
Output: -
Ans. <html>
<body>
<script language="javascript" type="text/javascript">
function isPrime(num) {
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return num > 1;
}
function printPrimeNumbers(n) {
for (let i = 2; i <= 50; i++) {
if (isPrime(i)) {
console.log(i);
}
}
}
printPrimeNumbers(100);
</script>
</body>
</html>
Output: -
11
13
17
19
23
29
31
37
41
43
47
Practical 3
Ans. Associative arrays are dynamic objects that the user redefines as
needed. When you assign values to keys in a variable of type Array, the
array is transformed into an object, and it loses the attributes and methods
of Array. The length attribute has no effect because the variable is no longer
of the Array type.
Ans. <html>
<body>
<p id="demo"></p>
<script language="javascript" type="text/javascript">
const cars = ["Tata", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
Output: -
Ans. <html>
<body>
<script language="javascript" type="text/javascript">
// Initial array
let fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
console.log('Initial Array:', fruits);
0..
Output: -
Initial Array:
After push():
After pop():
Removed Fruit:
Pineapple
After unshift():
After sort():
["Strawberry", "Orange", "Banana", "Apple"]
After reverse():
After splice():
Removed Fruits:
["Mango"]
Practical 4
Program: - 0
<html>
<body>
<script language="javascript" type="text/javascript">
// Global scope
var globalVar = "I am a global variable";
function exampleFunction() {
// Function (local) scope
var localVar = "I am a local variable";
console.log(globalVar); // Accessible (from global scope)
console.log(localVar); // Accessible (within function)
exampleFunction();
Output: -
I am a global variable
I am a local variable
I am block scoped
I am a global variable
Ans. You can call a JavaScript function directly from an HTML element using
an inline event handler like onclick, onmouseover, onload, etc.
Ans. <html>
<body>
<p id="demo"></p>
<script language="javascript" type="text/javascript">
function myFunction() {
return Math.PI;
}
document.getElementById("demo").innerHTML = myFunction();
</script>
</body>
</html>
Output: -
3.141592653589793
Ans. <html>
<body>
<script language="javascript" type="text/javascript">
// JavaScript function with two arguments
function addNumbers(num1, num2) {
var sum = num1 + num2;
console.log("The sum of " + num1 + " and " + num2 + " is: " + sum);
}
Output: -
Practical 5
Ans. <html>
<body>
<script language="javascript" type="text/javascript">
// Function to find the position of a character in a string
function findCharacterPosition(string, character) {
var position = string.indexOf(character);
if (position !== -1) {
console.log("The character '" + character + "' is at position: " +
position);0
} else {
console.log("The character '" + character + "' is not found in the
string.");
}
}
// Example usage
var myString = "Hello, World!";
var characterToFind = "W";
findCharacterPosition(myString, characterToFind);
</script>
</body>
</html>
Ans. <html>
<body>
<script language="javascript" type="text/javascript">
// Example strings
const exampleString = "Hello, welcome to the world of JavaScript!";
// Usage
const searchResult = customSearch(exampleString, /welcome/);
console.log('Search Result:', searchResult); // Outputs the index of the
match
Output: -
Split Result:
0: "Hello,"
1: "welcome"
2: "to"
3: "the"
4: "world"
5: "of"
6: "JavaScript!"
Substring Result:
welcome
Substr Result:
welcome
Syntax:
string.charCodeAt(index);
index: The position of the character in the string whose Unicode value
you want to retrieve. Indexing starts from 0.
Example: -
<html>
<body>
<script language="javascript" type="text/javascript">
var myString = "Hello";
var code = myString.charCodeAt(1); // Get the Unicode of the character at
index 1 (which is 'e')
console.log("The Unicode value of 'e' is: " + code);
</script>
</body>
</html>
Output: -
Explanation:
2. fromCharCode() Method
Syntax:
num1, num2, ...: These are the Unicode values you want to convert
to characters.
Example: -
<html>
<body>
<script language="javascript" type="text/javascript">
var char1 = String.fromCharCode(72); // Unicode for 'H'
var char2 = String.fromCharCode(101); // Unicode for 'e'
var char3 = String.fromCharCode(108); // Unicode for 'l'
var char4 = String.fromCharCode(108); // Unicode for 'l'
var char5 = String.fromCharCode(111); // Unicode for 'o'
</html>
Output: -
Explanation:
Practical 6
Q1 Explain Building blocks of form (Bhot bada hai ans appne hisab se cut kar
ke likhna )
Ans. Forms in HTML are used to collect user inputs and send them to a server
for processing. They are essential building blocks in creating interactive
websites. Below are the key building blocks (elements) of an HTML form,
along with brief descriptions:
1. <form> Element
The <form> element is the container for all input elements that make up the
form. It defines how the data will be sent and where the data will be sent to.
Key Attributes:
</form>
2. <input> Element
The <input> element is used to collect user input. The type of input is
controlled by the type attribute, and there are many types of inputs, such as
text, password, email, etc.
Example:
The <textarea> element is used for multi-line text input. Unlike <input>,
which is generally for short inputs, <textarea> is ideal for longer texts like
comments or descriptions.
Example:
4. <select> Element
The <select> element creates a drop-down list. Each item in the list is
defined using the <option> element.
Example:
<select name="country">
<option value="india">India</option>
<option value="usa">USA</option>
<option value="canada">Canada</option>
</select>
5. <label> Element
The <label> element provides a clickable label for form controls. Using
labels improves the accessibility of forms, especially for screen readers. It
can be associated with an input using the for attribute or by wrapping the
input inside the label.
Example:
<label for="email">Email:</label>
The <button> element is used to create clickable buttons. Unlike the <input
type="submit"> element, buttons can contain other elements like images
and allow for more customization.
Example:
Example:
<fieldset>
<legend>Personal Information</legend>
<label for="name">Name:</label>
</fieldset>
<body>
<form action="/submit" method="post">
<fieldset>
<legend>Personal Information</legend>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<label for="country">Country:</label>
<select id="country" name="country">
<option value="india">India</option>
<option value="usa">USA</option>
<option value="canada">Canada</option>
</select><br>
<label for="comments">Comments:</label><br>
<textarea id="comments" name="comments" rows="5"
cols="30"></textarea><br>
</fieldset>
</form>
</body>
</html>
Output: -
Ans. <html>
<body>
<form action="/submit" method="post">
<!-- Personal Details -->
<fieldset>
<legend>Personal Details</legend>
<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select><br><br>
<label for="address">Address:</label>
<textarea id="address" name="address" rows="4" required></textarea>
</fieldset>
<label for="percentage">Percentage/Grade:</label>
<input type="text" id="percentage" name="percentage" required><br><br>
</form>
</body>
</html>
Output: -
Q3 Create a form which display output as given below
Ans. <html>
<body>
<form>
<fieldset>
<!-- Username and Last Name fields -->
<label for="username">User Name:</label>
<input type="text" id="username" name="username"><br><br>
Practical 7
Q1 Write a function that logs the current mouse position (x, y) relative to the
browser window whenever the mouse moves.
Ans.
The logMousePosition function is called whenever the mouse moves
(mousemove event).
event.clientX and event.clientY provide the x and y coordinates of
the mouse relative to the browser window.
These coordinates are logged to the console each time the mouse is
moved.
Ans. <html>
<body>
<script language="javascript" type="text/javascript">
// Function to log mouse position
function logMousePosition(event) {
const x = event.clientX;
const y = event.clientY;
console.log(`Mouse Position - X: ${x}, Y: ${y}`);
}
</html>
Output: -
Mouse Position - X: 2, Y: 60
Mouse Position - X: 3, Y: 60
Mouse Position - X: 3, Y: 61
Mouse Position - X: 2, Y: 61
Ans. To log the key code of a pressed key in JavaScript, you can use the
keydown event listener and access the event.keyCode or event.which
property. In modern JavaScript, it's recommended to use event.code or
event.key for more reliable results across different browsers.
Here’s how you can log the key code of a pressed key:
<html>
<body>
<script language="javascript" type="text/javascript">
document.addEventListener('keydown', function(event) {
console.log("Key Code:", event.keyCode); // Old method (deprecated)
console.log("Key:", event.key); // Modern method (key value)
console.log("Code:", event.code); // Modern method (key code)
});
</script>
</body>
</html>
Output: -
Key Code: 65
Key: a
Code: KeyA
Practical 8
Q1 Write HTML Script that displays textboxes for accepting Name, Middle
name, Surname of the user and a Submit button. Write proper JavaScript
such that when the user clicks on submit button all textboxes must get
disabled and change the color to “RED”. and with respective labels.
Constructs the mailID as. @msbte.com and displays mail ID as message. (Ex.
If user enters Ranjeet as name and shergil as surname mail ID will be
constructed as Ranjeet.shergil@msbte.com).
Ans. <html>
<body>
<form id="userForm" onsubmit="generateEmailID(event)">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" required> <br><br>
<label for="middleName">Middle Name:</label>
<input type="text" id="middleName" required><br><br>
<label for="surname">Surname:</label>
<input type="text" id="surname" required><br><br>
<button type="submit">Submit</button>
</form>
<div id="output"></div>
<script language="javascript" type="text/javascript">
function generateEmailID(event) {
event.preventDefault(); // Prevent form submission
// Generate email ID
const emailID = `${firstName}.${surname}@msbte.com`;
// Display email ID
document.getElementById("output").textContent = `Generated Email ID: $
{emailID}`;
</html>
Output: -
Q2 Write a JavaScript to create three radio buttons for Fruit, Flower, Color
and one option list. Based on respective radio button selection by user fruit,
flower, color names are shown in option list according to.
Ans. <html>
<body>
<h2>Select a Category:</h2>
<h3>Options:</h3>
<!-- Dropdown for displaying options based on selection -->
<select id="optionsList">
<option>Select an option</option>
</select>
</html>
Output: -
Practical 9
When this code is executed, the message "User name is: John" is printed
in the console, allowing the developer to verify that the name variable has the
expected value.
Ans. The typeof operator in JavaScript is used to determine the data type of
a given value or variable. It’s a quick way to check whether a value is a
string, number, boolean, object, function, or another data type.
Syntax
typeof variableOrValue;
Example Usage
typeof 42; // Returns "number"
Ans. 1. parseInt()
2. parseFloat()
3. Number()
6. typeof
7. Array.isArray()
9. Math.random()
10. Date.now()
Syntax
function functionName(parameters) {
// Code
function calculateSquare(number) {
Q1 Write a JavaScript program which accept cookie values from user &
display them, also add a button to delete those values
Ans. <html>
<body>
<form name="form1">
Enter Name: <input type="text" id="username" name="username" />
<input type="button" value="Create Cookie" onclick="createCookie()" />
<input type="button" value="Read Cookie" onclick="readCookie()" />
<input type="button" value="Delete Cookie" onclick="deleteCookie()" />
</form>
<p id="cookieValue"></p>
<script type="text/javascript">
// Function to create a cookie
function createCookie() {
var username = document.getElementById("username").value;
if (username) {
document.cookie = "UserName=" + encodeURIComponent(username) + ";
path=/;"; // Ensure proper encoding
alert("Cookie created: " + document.cookie); // Debugging message
} else {
alert("Please enter a username");
}
}
Output
Practical 11
1. Explain open() method of window object with syntax & Example.
Ans. The open() method in JavaScript’s window object is used to open a new browser window or
tab or load a URL in a specified frame.
Syntax:
window.open(URL, name, specs, replace);
URL (optional): The URL to open. Defaults to an empty page if omitted.
name (optional): The target window name (_blank, _self, etc.) or a
unique name.
specs (optional): A string of features/size for the new window (e.g.,
"width=500, height=500").
replace (optional): Boolean, if true replaces the current page in the
history.
Example:
window.open("https://www.example.com", "_blank",
"width=600,height=400");
Output: -
This opens example.com in a new window/tab with specified dimensions.
Ans. The innerHTML property in JavaScript is used to get or set the HTML
content inside an element. It allows you to dynamically change or insert
HTML within a specified element.
Syntax:
Example:
<script type=“text/javascript”>
</script>
In this example, the innerHTML of the <div> element is updated from "Hello,
World!" to "Hello, JavaScript!".
Ans. To open multiple windows in JavaScript, you can use the window.open()
method multiple times, assigning each to a different variable so they can be
managed separately. Each call to window.open() opens a new browser
window or tab (depending on browser settings).
Syntax:
Example:
googleWindow.focus();
bingWindow.focus();
In this example, two separate windows are opened, one for Google and one
for Bing, each with specific dimensions. The focus() method is used to bring
each window to the front.
Syntax
window.onfocus = function() {
};
Example
<html>
<body>
<script type="text/javascript">
window.onfocus = function() {
};
</script>
</body>
</html>
Practical 12
<html>
<body>
<script type="text/javascript">
let text = "Hello123";
let pattern = /\d+/;
// test() method
console.log(pattern.test(text)); // true
// exec() method
console.log(pattern.exec(text)); // ["123"]
// match() method
console.log(text.match(pattern)); // ["123"]
// replace() method
console.log(text.replace(pattern, "456")); // "Hello456"
</script>
</body>
</html>
Ans. This program finds characters in a string that do not match a specific
pattern.
<html>
<body>
<script type="text/javascript">
let text = "abc123";
let pattern = /[^a-z]/g; // Find non-lowercase letters
let nonMatching = text.match(pattern);
console.log("Non-matching characters:", nonMatching);
</script>
</body>
</html>
Output: -
Ans. This program finds characters that are not digits in a given string.
<html>
<body>
<script type="text/javascript">
let text = "abc123";
let pattern = /\D/g; // Find non-digit characters
let nonDigits = text.match(pattern);
console.log("Non-digit characters:", nonDigits);
</script>
</body>
</html>
Output: -
<html>
<body>
<script type="text/javascript">
let text = "This is an example text.";
let pattern = /example/;
let isMatch = pattern.test(text);
Output: -
Pattern found: true
Practical 13
Ans. This JavaScript program displays the image of a fruit when the user
hovers over its name.
<html>
<body>
<h3>Hover over the fruit name to see the image:</h3>
<script type="text/javascript">
function showImage(fruit) {
let image = document.getElementById("fruitImage");
image.style.display = "block";
image.src = fruit + ".jpg"; // Assuming images are named mango.jpg,
apple.jpg, banana.jpg
}
function hideImage() {
let image = document.getElementById("fruitImage");
image.style.display = "none";
}
</script>
</body>
</html>
Output: -
In this example, you’ll need images named mango.jpg, apple.jpg, and
banana.jpg in the same directory. When you hover over the fruit name, the
corresponding image will be displayed.
Ans. This JavaScript program not only shows the image of the fruit but also
opens an alert or pop-up window displaying the benefits of each fruit.
<html>
<body>
<h3>Hover over the fruit name to see the image and benefits:</h3>
<div onmouseover="showImageAndBenefits('mango')"
onmouseout="hideImage()">Mango</div>
<div onmouseover="showImageAndBenefits('apple')"
onmouseout="hideImage()">Apple</div>
<div onmouseover="showImageAndBenefits('banana')"
onmouseout="hideImage()">Banana</div>
<script type="text/javascript">
function showImageAndBenefits(fruit) {
let image = document.getElementById("fruitImage");
image.style.display = "block";
image.src = fruit + ".jpg"; // Assuming images are named mango.jpg,
apple.jpg, banana.jpg
let benefits = {
mango: "Mango is rich in vitamin C and antioxidants.",
apple: "Apple helps in digestion and boosts immunity.",
banana: "Banana provides potassium and energy."
};
function hideImage() {
let image = document.getElementById("fruitImage");
image.style.display = "none";
}
</script>
</body>
</html>
3. Features of Rollover
Ans. Rollover effects provide visual feedback when the user interacts with an
element by hovering or "rolling over" it. Here are the main features of
rollover effects:
Practical 14
1. Creating a Pull-Down Menu
Ans. A pull-down menu allows users to select one item from a list by clicking
on the drop-down. It’s often implemented using the <select> and <option>
HTML elements.
<script type="text/javascript">
document.getElementById("fruitMenu").onchange = function() {
alert("You selected: " + this.value);
};
</script>
</body>
</html>
Output: -
In this example:
The <select> element creates a pull-down menu where users can pick
a fruit.
When a user selects a fruit, an alert displays the selected option.
2. Floating Menu
Ans. A floating menu remains in a fixed position on the page as the user
scrolls, providing easy access to navigation or important actions. This effect
is typically achieved with CSS position: fixed or position: sticky and
can be enhanced with JavaScript.
Output: -
<label for="state">State/Province:</label>
<select id="state">
<option value="">--Select State--</option>
</select>
<script type="text/javascript">
function updateStates() {
const country = document.getElementById("country").value;
const stateSelect = document.getElementById("state");
Output: -
Practical 15
1. List ways of protecting your web page and describe any one of them
Use passwords that are at least eight characters long and include a combination
of letters, numbers, and special characters. Avoid using words that are easy to
find in a dictionary or that reference personal information.
2. Use a web application firewall (WAF)
3. Install an SSL certificate
4.Run regular backups
5.Update your software
6.Use multi-factor authentication (MFA)
7.Limit login attempts
8.Educate your employees
2. JavaScript Program to Hide the Email Address
Ans. The following script hides part of an email address, making it less visible to web
scrapers but still understandable for users:
<html>
<body>
<p id="emailDisplay">Email: </p>
<script type="text/javascript">
// Email hiding function
function hideEmail(user, domain) {
const email = user + "@" + domain;
document.getElementById("emailDisplay").innerText += email;
}
Output: -
In this example:
The function hideEmail constructs the email using parameters for the
user and domain, hiding it from direct display in HTML.
Ans. This script disables the right-click context menu on the web page,
preventing users from using "right-click" actions like "Save As" or "View
Source":
<html>
<script type="text/javascript">
window.onload = function () {
document.addEventListener("contextmenu", function (e) {
e.preventDefault();
}, false);
}
</script>
<body>
<h3>Right click on screen,Context Menu is disabled</h3>
</body>
</html>
Practical 16
Example:
<html>
<body>
<a id="bannerLink" href="#" target="_blank">
<img id="bannerAd" src="banner1.jpg" alt="Advertisement Banner"
width="300" height="100">
</a>
<script type="text/javascript">
// Function to link the banner to a URL
function setBanner(url, imageSrc) {
document.getElementById("bannerLink").href = url; // Set the link
for the banner
document.getElementById("bannerAd").src = imageSrc; // Set the banner
image
}
Output: -
2. Create a slideshow with the group of three images. Also
simulate the next and previous transition between slides in your
java script.
<html>
<body>
<div>
<img id="slideshowImage" src="image1.jpg" width="300" height="200"
alt="Slideshow Image">
</div>
<br>
<button onclick="prevSlide()">Previous</button>
<button onclick="nextSlide()">Next</button>
<script type="text/javascript">
// Array of image sources
const images = ["image1.jpg", "image2.jpg", "image3.jpg"];
let currentIndex = 0;
Output: -