CSS Summer 23

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 38

CSS Summer 23 Question Paper

Attempt any FIVE of the following : 10

(a) State the ways to display the output in JavaScript.


Ans.
Method Description Example
console.l Prints output to the browser's console console.log('Hello, world!');
og()
alert() Pops up an alert dialog box with the alert('Hello, world!');
specified message
documen Writes content directly to the HTML document.write('Hello, world!');
t.write() document
innerHT Updates the HTML content of an element document.getElementById('output').inn
ML erHTML = 'Hello, world!';
console. Outputs an error message to the console console.error('This is an error
error() message.');
console. Outputs a warning message to the console console.warn('This is a warning
warn() message.');
window. Displays a prompt dialog box that lets the var userInput = window.prompt('Please
prompt() user input a value enter your name:');
window.c Displays a dialog box with a specified var result = window.confirm('Are you
onfirm() message and OK/Cancel buttons sure?');
(b) List the logical operators in JavaScript with description.
Ans.

(c) Write JavaScript to create a object “student” with properties roll number, name,
branch, year. Delete branch property and display remaining properties of student object.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Object</title>
</head>
<body>
<h1>Student Object Example</h1>
<div id="output"></div>

<script>
// Create the student object
let student = {
rollNumber: 101,
name: "John Doe",
branch: "Computer Science",
year: "Sophomore"
};

// Delete the branch property


delete student.branch;

// Display the remaining properties


let outputDiv = document.getElementById("output");
for (let key in student) {
if (student.hasOwnProperty(key)) {
outputDiv.innerHTML += `<p>${key}: ${student[key]}</p>`;
}
}
</script>
</body>
</html>

(d) Write a JavaScript that initializes an array called Colors with the names of 3 Colors
and display the array elements.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Colors Array Example</title>
</head>
<body>
<h1>Colors Array</h1>
<div id="output"></div>

<script>
// Initialize the Colors array with 3 color names
let Colors = ["Red", "Green", "Blue"];

// Get the output div to display the colors


let outputDiv = document.getElementById("output");

// Loop through the array and display each color


Colors.forEach(function(color) {
outputDiv.innerHTML += `<p>${color}</p>`;
});
</script>
</body>
</html>

(e) Explain calling a function with arguments in JavaScript with example.


Ans.
1. Logical AND (&&)
Description: Returns true if both operands are true; otherwise, it returns false.
Example:
let result = true && false; // result is false

2. Logical OR (||)
Description: Returns true if at least one of the operands is true; otherwise, it returns false.
Example:
let result = true || false; // result is true

3. Logical NOT (!)


Description: Reverses the logical state of its operand. If the operand is true, it returns false; if
the operand is false, it returns true.
Example:
let result = !true; // result is false

4. Nullish Coalescing (??)


Description: Returns the right-hand operand if the left-hand operand is null or undefined;
otherwise, it returns the left-hand operand.
Example:
let result = null ?? "default"; // result is "default"

5. Optional Chaining (?.)


Description: Allows you to safely access deeply nested properties of an object without having to
explicitly check if each reference in the chain is null or undefined.
Example:
let user = { name: "John" };
let result = user?.address?.city; // result is undefined

(f) Enlist any four mouse events with their use.


Ans.

(g) State any four properties of Navigator object.


Ans.
Here are four common mouse events in JavaScript along with their uses:
1. click
 Description: Triggered when an element is clicked (usually with the left mouse button).
 Use: Commonly used to handle user clicks on buttons, links, or other clickable elements.
 Example:
document.getElementById("myButton").addEventListener("click", function() {
alert("Button was clicked!");
});
2. dblclick
 Description: Triggered when an element is double-clicked.
 Use: Used for actions that require double-clicking, such as opening a file or zooming in.
 Example:
document.getElementById("myElement").addEventListener("dblclick", function() {
alert("Element was double-clicked!");
});
3. mouseover
 Description: Triggered when the mouse pointer hovers over an element.
 Use: Often used to show tooltips, change styles, or trigger animations when the user hovers over an element.
 Example:
document.getElementById("myElement").addEventListener("mouseover", function() {
this.style.backgroundColor = "yellow";
});
4. mouseout
 Description: Triggered when the mouse pointer leaves an element.
 Use: Used to revert changes made during the mouseover event, such as restoring the original styles.
 Example:
document.getElementById("myElement").addEventListener("mouseout", function() {
this.style.backgroundColor = "";
});

2.Attempt any THREE of the following : 12

(a) Explain getter and setter properties in JavaScript with 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",

/* Accessor properties (getters) */


get color() {
return this.defColor;
},
get make() {
return this.defMake;
},

/* Accessor properties (setters) */


set color(newColor) {
this.defColor = newColor;
},
set make(newMake) {
this.defMake = newMake;
}
};
document.write("Car color:" + myCar.color + " Car Make: "+myCar.make)
/* Calling the setter accessor properties */
myCar.color = "red";
myCar.make = "Audi";
/* Checking the new values with the getter accessor properties */
document.write("<p>Car color:" + myCar.color); // red
document.write(" Car Make: "+myCar.make); //Audi
</script>
</head>
</body>
</html>

(b) Explain Object creation in JavaScript using ‘new’ keyword with adding properties and
methods with example.
Ans.In JavaScript, you can create objects using the new keyword along with a constructor function. This approach allows
you to define properties and methods for the object. Here's a detailed explanation with an example:
Steps for Object Creation Using new
1. Define a Constructor Function: A constructor function is a special type of function that is used to create
objects. It typically starts with an uppercase letter by convention.
2. Add Properties: Inside the constructor function, you can assign properties to the object using the this keyword.
3. Add Methods: You can also define methods inside the constructor function or add them to the prototype for
shared methods among all instances.
4. Create Objects: Use the new keyword to create instances of the object.
Example
Here's a complete example demonstrating object creation using the new keyword:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Object Creation Example</title>
</head>
<body>
<h1>Object Creation Using 'new'</h1>
<div id="output"></div>

<script>
// Step 1: Define the constructor function
function Student(rollNumber, name, branch, year) {
// Step 2: Adding properties
this.rollNumber = rollNumber;
this.name = name;
this.branch = branch;
this.year = year;
}

// Step 3: Adding a method to the prototype


Student.prototype.getDetails = function() {
return `Roll Number: ${this.rollNumber}, Name: ${this.name}, Branch: ${this.branch},
Year: ${this.year}`;
};

// Step 4: Create instances using the 'new' keyword


let student1 = new Student(101, "Alice", "Computer Science", "Sophomore");
let student2 = new Student(102, "Bob", "Mathematics", "Junior");

// Display the details of the students


let outputDiv = document.getElementById("output");
outputDiv.innerHTML += `<p>${student1.getDetails()}</p>`;
outputDiv.innerHTML += `<p>${student2.getDetails()}</p>`;
</script>
</body>
</html>

(c) Write a JavaScript for loop that will iterate from 1 to 15. For each iteration, it
will check if the current number is odd or even and display a message to the screen.
Sample Output : “1 is odd”
“2 is even” ............ .............
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Odd or Even Checker</title>
</head>
<body>
<h1>Odd or Even Checker</h1>
<div id="output"></div>

<script>
// Get the output div to display the messages
let outputDiv = document.getElementById("output");
// Iterate from 1 to 15
for (let i = 1; i <= 15; i++) {
// Check if the number is odd or even
if (i % 2 === 0) {
outputDiv.innerHTML += `<p>${i} is even</p>`;
} else {
outputDiv.innerHTML += `<p>${i} is odd</p>`;
}
}
</script>
</body>
</html>

(d) Write the use of charCodeAt() and from CharCode() method with syntax and example.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>charCodeAt() and fromCharCode() Example</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
color: #333;
margin: 20px;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #0056b3;
}
p{
margin: 10px 0;
}
.result {
font-weight: bold;
color: #d9534f; /* Bootstrap danger color */
}
</style>
</head>
<body>
<h1>Using charCodeAt() and fromCharCode()</h1>

<p id="charCodeExample"></p>
<p id="fromCharCodeExample"></p>

<script>
// Example of charCodeAt()
let str = "Hello";
let charCode = str.charCodeAt(0); // Get the Unicode value of 'H'
document.getElementById("charCodeExample").innerHTML =
`The charCodeAt(0) of '${str}' is <span class="result">${charCode}</span>.`;

// Example of fromCharCode()
let char = String.fromCharCode(72); // Create a string from Unicode value 72
document.getElementById("fromCharCodeExample").innerHTML =
`String.fromCharCode(72) returns '<span class="result">${char}</span>'.`;
</script>
</body>
</html>

3. Attempt any THREE of the following : 12


(a) Differentiate between push() and join() method of array object with respect to use,
syntax, return value and example.
Ans.
Feature push() Method join() Method
Use Adds one or more elements to the end of Joins all elements of an array into a
an array. single string.
Syntax array.push(element1, element2, ..., array.join(separator)
elementN)
Return Returns the new length of the array after Returns a string with all elements
Value adding elements. joined by the separator.
Example javascript let fruits = ['Apple', 'Banana']; javascript let fruits = ['Apple',
let newLength = fruits.push('Cherry'); 'Banana']; let result = fruits.join(', ');
console.log(newLength); // Output: 3 console.log(result); // Output: "Apple,
console.log(fruits); // Output: ['Apple', Banana"
'Banana', 'Cherry']
(b) Write JavaScript code to perform following operations on string. (Use split() method)
Input String : “Sudha Narayana Murthy” Display output as
First Name : Sudha
Middle Name : Narayana
Last Name : Murthy
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Split String Example</title>
</head>
<body>
<h1>Extract First, Middle, and Last Names</h1>
<div id="output"></div>
<script>
// Input string
let inputString = "Sudha Narayana Murthy";

// Use split() method to divide the string by spaces


let nameParts = inputString.split(" ");

// Extract first, middle, and last names from the array


let firstName = nameParts[0];
let middleName = nameParts[1];
let lastName = nameParts[2];

// Display the output


document.getElementById("output").innerHTML = `
<p>First Name: ${firstName}</p>
<p>Middle Name: ${middleName}</p>
<p>Last Name: ${lastName}</p>
`;
</script>
</body>
</html>

(c) Explain splice() method of array object with syntax and example.
Ans. The JavaScript array splice() method is used to add/remove the elements to/from the existing array. It returns the
removed elements from an array. The splice() method also modifies the original array.
Syntax:
array.splice(start, deleteCount, item1, item2, ...);
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array splice() Method Example</title>
</head>
<body>
<h1>JavaScript Array splice() Method</h1>
<div id="output"></div>

<script>
// Original array
let fruits = ["Apple", "Banana", "Mango", "Pineapple", "Grapes"];

// Display original array


let output = `<p>Original Array: ${fruits}</p>`;

// Example 1: Removing elements


// Remove 1 element from index 2
let removedItems = fruits.splice(2, 1);
output += `<p>After Removing: ${fruits}</p>`;
output += `<p>Removed Item(s): ${removedItems}</p>`;

// Example 2: Adding elements


// Add two elements at index 1
fruits.splice(1, 0, "Orange", "Peach");
output += `<p>After Adding: ${fruits}</p>`;

// Example 3: Replacing elements


// Replace 2 elements starting from index 3
let replacedItems = fruits.splice(3, 2, "Strawberry", "Blueberry");
output += `<p>After Replacing: ${fruits}</p>`;
output += `<p>Replaced Item(s): ${replacedItems}</p>`;

// Display all results


document.getElementById("output").innerHTML = output;
</script>
</body>
</html>
(d) Explain how to create and read Persistent Cookies in JavaScript with example.
Ans.Persistent cookies in JavaScript are cookies that remain on the user's device for a specified duration, even after the
browser is closed. They are typically used for storing user preferences, authentication tokens, and other data that needs to
persist across sessions.
Creating Persistent Cookies in JavaScript
To create a persistent cookie, you set the cookie with an expiration date. This can be done using the
document.cookieproperty.
Syntax to Set a Cookie
document.cookie = "name=value; expires=date; path=path";
name=value: The name and value of the cookie.
expires: The date and time when the cookie should expire. After this time, the cookie will be deleted. It is specified in
UTC format, often using JavaScript’s Date object.
path: Specifies the path for which the cookie is valid (optional). If not specified, the cookie is only available on the current
page.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Persistent Cookie Example</title>
</head>
<body>
<h1>Persistent Cookies in JavaScript</h1>
<button onclick="setCookie('username', 'JohnDoe', 7)">Set Cookie</button>
<button onclick="readCookie('username')">Read Cookie</button>
<div id="output"></div>

<script>
// Function to set a persistent cookie
function setCookie(name, value, days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); // Convert days to
milliseconds
let expires = "expires=" + date.toUTCString();
document.cookie = `${name}=${value}; ${expires}; path=/`; // Setting the cookie
document.getElementById("output").innerText = `Cookie "${name}" set with value "$
{value}".`;
}

// Function to read a cookie by name


function readCookie(name) {
let cookies = document.cookie.split("; "); // Split cookie string into individual cookies
for (let cookie of cookies) {
let [cookieName, cookieValue] = cookie.split("="); // Split each cookie into name and
value
if (cookieName === name) {
document.getElementById("output").innerText = `Cookie "${name}" has value "$
{cookieValue}".`;
return cookieValue;
}
}
document.getElementById("output").innerText = `Cookie "${name}" not found.`;
return null;
}
</script>
</body>
</html>

4.Attempt any THREE of the following : 12

(a) Explain test() and exec() method of Regular Expression object with example.
Ans.

(b) List ways of protecting your web page and describe any one of them.
Ans.Ways of protecting Web Page:
1)Hiding your source code
2)Disabling the right MouseButton
3) Hiding JavaScript
4) Concealing E-mail address.
1) Hiding your source code
The source code for your web page—including your JavaScript—is stored in the
cache, the part of computer memory where the browser stores web pages that
were requested by the visitor. A sophisticated visitor can access the cache and
thereby gain access to the web page source code.
However, you can place obstacles in the way of a potential peeker. First, you can
disable use of the right mouse button on your site so the visitor can't access the
View Source menu option on the context menu. This hides both your HTML code
and your JavaScript from the visitor.
Nevertheless, the visitor can still use the View menu's Source option to display
your source code. In addition, you can store your JavaScript on your web server
instead of building it into your web page. The browser calls the JavaScript from
the web server when it is needed by your web page.
Using this method, the JavaScript isn't visible to the visitor, even if the visitor
views the source code for the web page.
2)Disabling the right MouseButton
The following example shows you how to disable the visitor's right mouse button
while the browser displays your web page. All the action occurs in the JavaScript
that is defined in the <head> tag of the web page.
The JavaScript begins by defining the BreakInDetected() function. This function
is called any time the visitor clicks the right mouse button while the web page is
displayed. It displays a security violation message in a dialog box whenever a
visitor clicks the right mouse button
The BreakInDetected() function is called if the visitor clicks any button other
than the left mouse button.
Example:
<html>
<head>
<title>Lockout Right Mouse Button</title>
<script language=JavaScript>
function BreakInDetected(){
alert('Security Violation')
return false
}
function NetscapeBrowser(e){
if (document.layers||
document.getElementById&&!document.all){
if (e.which==2||e.which==3){
BreakInDetected()
return false
}
}
}
function InternetExploreBrowser(){
if (event.button==2){
BreakInDetected()
return false
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN)
document.onmousedown=NetscapeBrowser()
}
else if (document.all&&!document.getElementById){
document.onmousedown=InternetExploreBrowser()
}
document.oncontextmenu=new Function(
"BreakInDetected();return false")
</script>
</head>
<body>
<table width="100%" border=0>
<tbody>
<tr vAlign=top>
<td width=50>
<a>
<ing height=92 src="rose.jpg"
width=70 border=0
onmouseover="src='rose1.jpg'"
onmouseout="src='rose.jpg'">
</a>
</td>
<td>
<img height=1 src="" width=10>
</td>
<td>
<a>
<cTypeface:Bold><u> Rose Flower</U></b>
</a>
</font><font face="arial, helvetica, sans-serif"
size=-1><BR>Rose Flower
</tr>
</tbody>
</table>
</body>
</html>
3) Hiding JavaScript
You can hide your JavaScript from a visitor by storing it in an external fi le on
your web server. The external fi le should have the .js fi le extension. The browser
then calls the external file whenever the browser encounters a JavaScript element
in the web page. If you look at the source code for the web page, you'll see
reference to the external .js fi le, but you won't see the source code for the
JavaScript.
The next example shows how to create and use an external JavaScript file. First
you must tell the browser that the content of the JavaScript is located in an
external
file on the web server rather than built into the web page. You do this by assigning
the fi le name that contains the JavaScripts to the src attribute of the <script>
tag, as shown here:
<script src="MyJavaScripts.js"
language="Javascript" type="text/javascript">
Next, you need to defi ne empty functions for each function that you define in the
external JavaScript fi le.
<html >
<head>
<title>Using External JavaScript File</title>
<script src="myJavaScript.js" language="Javascript" type="text/javascript">
function OpenNewWindow(book) {
}
</script>
</head>
<body>
<tablewidth="100%" border=0>
<tbody>
<tr vAlign=top>
<td width=50>
<a>
<img height=92 src="rose.jpg" width=70 border=0 name='cover'>
</a>
</td>
<td>
<img height=1 src="" width=10>
</td>
<td>
<a onmouseover="OpenNewWindow(1)" onmouseout="MyWindow.close()">
<b><u>Rose </u></b>
</a>
<br>
<a onmouseover="OpenNewWindow(2)" onmouseout="MyWindow.close()">
<b><u>Sunflower</U></b>
</a>
<br>
<A onmouseover="OpenNewWindow(3)" onmouseout="MyWindow.close()">
<b><u>Jasmine </u></b>
</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
The final step is to create the external JavaScript fi le. You do this by placing all
function definitions into a new fi le and then saving the fi le using the .js
extension.
MyJavaScript.js file:
function OpenNewWindow(book) {
if (book== 1)
{
document.cover.src='rose.jpg'
MyWindow = window.open('', 'myAdWin', 'titlebar=0 status=0, toolbar=0,
location=0, menubar=0, directories=0, resizable=0, height=50,
width=150,left=500,top=400')
MyWindow.document.write( 'Rose flower')
}
if (book== 2)
{
document.cover.src='sunflower.jpeg'
MyWindow = window.open('', 'myAdWin', 'titlebar=0 status=0, toolbar=0,
location=0, menubar=0, directories=0, resizable=0, height=50,
width=150,left=500,top=500')
MyWindow.document.write( 'sunflower flower')
}
if (book== 3)
{
document.cover.src='jasmine.gif'
MyWindow = window.open('', 'myAdWin', 'titlebar=0
status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=0,
height=50,
width=150,left=500,top=600')
MyWindow.document.write( 'Jasmine Flower')
}
}
After you create the external JavaScript fi le, defi ne empty functions for each
function that is contained in the external JavaScript fi le, and reference the
external
JavaScript fi le in the src attribute of the <script> tag, you're all set.
4) Concealing E-mail address:
Many of us have endured spam at some point and have probably blamed every
merchant we ever patronized for selling our e-mail address to spammers. While
e-mail addresses are commodities, it's likely that we ourselves are the culprits
who invited spammers to steal our e-mail addresses.
Here's what happens: Some spammers create programs called bots that surf the
Net looking for e-mail addresses that are embedded into web pages, such as those
placed there by developers to enable visitors to contact them. The bots then strip
these e-mail addresses from the web page and store them for use in a spam attack.
This technique places developers between a rock and a hard place. If they place
their e-mail addresses on the web page, they might get slammed by spammers. If
they don't display their e-mail addresses, visitors will not be able to get in touch
with the developers.
The solution to this common problem is to conceal your e-mail address in the
source code of your web page so that bots can't fi nd it but so that it still appears
on the web page. Typically, bots identify e-mail addresses in two ways: by the
mailto: attribute that tells the browser the e-mail address to use when the visitor
wants to respond to the web page, and by the @ sign that is required of all e-mail
addresses. Your job is to confuse the bots by using a JavaScript to generate the
e-mail address dynamically. However, you'll still need to conceal the e-mail
address in your JavaScript, unless the JavaScript is contained in an external
JavaScript file, because a bot can easily recognize the mailto: attribute and the @
sign in a JavaScript.
Bots can also easily recognize when an external fi le is referenced. To conceal an
e-mail address, you need to create strings that contain part of the e-mail address
and then build a JavaScript that assembles those strings into the e-mail address,
which is then written to the web page.
The following example illustrates one of many ways to conceal an e-mail address.
It also shows you how to write the subject line of the e-mail. We begin by
creating four strings:
• The first string contains the addressee and the domain along with symbols &, *,
and _ (underscore) to confuse the bot.
• The second and third strings contain portions of the mailto: attribute name.
Remember that the bot is likely looking for mailto:.
• The fourth string contains the subject line. As you'll recall from your HTML
training, you can generate the TO, CC, BCC, subject, and body of an e-mail from
within a web page.
You then use these four strings to build the e-mail address. This process starts by
using the replace() method of the string object to replace the & with the @ sign
and the * with a period (.). The underscores are replaced with nothing, which is
the
same as simply removing the underscores from the string.
All the strings are then concatenated and assigned to the variable b, which is then
assigned the location attribute of the window object. This calls the e-mail program
on the visitor's computer and populates the TO and Subject lines with the strings
generated by the JavaScript.
<html>
<head>
<title>Conceal Email Address</title>
<script>
function CreateEmailAddress(){
var x = manish*c_o_m'
var y = 'mai'
var z = 'lto'
var s = '?subject=Customer Inquiry'
x = x.replace('&','@')
x = x.replace('*','.')
x = x.replace('_','')
x = x.replace('_','')
var b = y + z +':'+ x + s
window.location=b
}
-->
</script>
</head>
<body>
<input type="button" value="Help"
onclick="CreateEmailAddress()">
</body>
</html>

(c) Explain how to create and display Rotating Banner in JavaScript with example.
Ans.To create a rotating banner in JavaScript, we can use an array to store image URLs or text, and set a timer to update
the banner content at specific intervals. This example will demonstrate creating an image-based rotating banner with
JavaScript, CSS, and HTML.
Steps to Create a Rotating Banner
1. HTML Structure: Create an HTML element to serve as the banner display area.
2. CSS Styling: Style the banner container to set the size and make the transitions smooth.
3. JavaScript Logic: Use JavaScript to rotate through banner items (images or text) periodically.
Example Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rotating Banner Example</title>
<style>
/* Banner container styling */
#banner {
width: 300px;
height: 200px;
border: 2px solid #333;
overflow: hidden;
position: relative;
text-align: center;
}

/* Image styling */
#banner img {
width: 100%;
height: 100%;
object-fit: cover;
transition: opacity 0.5s ease-in-out;
}
</style>
</head>
<body>

<h2>Rotating Banner</h2>
<div id="banner">
<img src="https://via.placeholder.com/300x200?text=Image+1" alt="Banner Image 1">
</div>

<script>
// Array of image URLs
const images = [
"https://via.placeholder.com/300x200?text=Image+1",
"https://via.placeholder.com/300x200?text=Image+2",
"https://via.placeholder.com/300x200?text=Image+3"
];

let currentIndex = 0; // Track the current image index

// Function to rotate the banner images


function rotateBanner() {
currentIndex = (currentIndex + 1) % images.length; // Move to the next image
const banner = document.getElementById("banner");
const img = banner.querySelector("img");

// Change the source of the image to the next one in the array
img.style.opacity = 0; // Fade out transition
setTimeout(() => {
img.src = images[currentIndex];
img.style.opacity = 1; // Fade in transition
}, 500); // Duration of fade-out effect
}

// Set interval to call rotateBanner every 3 seconds


setInterval(rotateBanner, 3000);
</script>

</body>
</html>
(d) Explain text and image rollover with suitable example.
Ans.Rollover means a webpage changes when the user moves his or her mouse over an object
on the page. It is often used in advertising. There are two ways to create rollover, using
plain HTML or using a mixture of JavaScript and HTML. We will demonstrate the creation
of rollovers using both methods.
The keyword that is used to create rollover is the <onmousover> event.
For example, we want to create a rollover text that appears in a text area. The text “What
is rollover?†appears when the user place his or her mouse over the text area and the
rollover text changes to “Rollover means a webpage changes when the user moves his or
her mouse over an object on the page†when the user moves his or her mouse away from
the text area.
The HTML script is shown in the following example:
Example:
<html>
<head></head>
<Body>
<textarea rows="2" cols="50" name="rollovertext" onmouseover="this.value='What
is rollover?'"
onmouseout="this.value='Rollover means a webpage changes when the user moves
his or her mouse over an object on the page'"></textarea>
</body>
</html>

(e) What is Status bar and how to display moving message on the status line of a window
using JavaScript ?
Ans.The status bar is a small area at the bottom of a browser window or application window that typically provides
information about the current state, actions, or context of the window. In the past, the status bar was frequently used in
web browsers and applications to display various types of messages, such as link destinations when hovering over a link,
loading progress, or error messages.
Characteristics of the Status Bar
1. Location:
a. Usually located at the bottom of the browser or application window.
2. Information Displayed:
a. Page Loading Status: Shows loading progress or messages like "Loading..." when a page is still
rendering.
b. Link Information: Displays the URL when a user hovers over a hyperlink, indicating where the link
will lead.
c. Error Messages or Warnings: Shows network-related issues, errors, or warnings.
d. Additional Information: In desktop applications, it can display things like coordinates (in graphic
software), word count (in word processors), or other useful data depending on the application.
3. JavaScript Control:
a. JavaScript can set the window.status property to display custom messages in the status bar, but modern
browsers have restricted this feature due to security and UX reasons.
4. Modern Usage:
a. Most modern browsers (such as Chrome, Firefox, and Edge) no longer have a visible status bar by
default.
b. Status-related information has largely moved to temporary overlays or tooltips near the bottom of the
screen, or to the address bar.
Example of Status Bar in Browsers
In older browsers or custom applications, you might see:
 A message like "Loading page..." while a new page loads.
 A URL preview when hovering over a link.
 Custom messages set by JavaScript (if supported), such as "Welcome to our site!".

In modern web to display a moving (scrolling) message on the status line (the status bar) of a window using JavaScript,
you can create a loop that updates the window.status property repeatedly to create a scrolling effect. The window.status is
an old technique, as modern browsers may not fully support setting messages in the status bar due to security and UX
reasons. However, if you want to experiment with it, here is how you can do it.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scrolling Status Line Message</title>
</head>
<body>

<script>
// Message to display
let message = " Welcome to our website! "; // Initial message
let position = 0; // Starting position of the scrolling message

// Function to update the status message


function scrollMessage() {
// Scroll by incrementing the position
let displayMessage = message.substring(position) + message.substring(0, position);
window.status = displayMessage; // Set the status bar text

// Update the position for the next scroll


position = (position + 1) % message.length; // Loop back to start

// Call the function again after a delay


setTimeout(scrollMessage, 150); // Scroll speed
}

// Start scrolling message


scrollMessage();
</script>

</body>
</html>

5.Attempt any TWO of the following : 12

(a) Write HTML code to design a form that displays two textboxes for accepting two
numbers, one textbox for accepting result and two buttons as ADDITION and
SUBTRACTION. Write proper JavaScript such that when the user clicks on any one of the
button, respective operation will be performed on two numbers and result will be displayed
in result textbox.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
}

.calculator {
max-width: 300px;
margin: auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

input[type="number"] {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 4px;
}

button {
width: 48%;
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
margin: 5px 1%;
font-size: 16px;
}

button:hover {
opacity: 0.9;
}

.add {
background-color: #28a745;
color: white;
}
.subtract {
background-color: #dc3545;
color: white;
}

#result {
background-color: #f8f9fa;
color: #333;
}
</style>
</head>
<body>

<div class="calculator">
<h2>Simple Calculator</h2>
<input type="number" id="number1" placeholder="Enter first number" required>
<input type="number" id="number2" placeholder="Enter second number" required>
<input type="text" id="result" placeholder="Result" disabled>
<div>
<button class="add" onclick="addNumbers()">ADDITION</button>
<button class="subtract" onclick="subtractNumbers()">SUBTRACTION</button>
</div>
</div>
<script>
function addNumbers() {
// Get the values from the input fields
const num1 = parseFloat(document.getElementById("number1").value);
const num2 = parseFloat(document.getElementById("number2").value);
// Perform addition
const sum = num1 + num2;
// Display the result
document.getElementById("result").value = sum;
}
function subtractNumbers() {
// Get the values from the input fields
const num1 = parseFloat(document.getElementById("number1").value);
const num2 = parseFloat(document.getElementById("number2").value);
// Perform subtraction
const difference = num1 - num2;
// Display the result
document.getElementById("result").value = difference;
}
</script>
</body>
</html>

(b) Write HTML code to design a form that displays two buttons START and STOP. Write
a JavaScript code such that when user clicks on START button, real time digital clock will
be displayed on screen. When user clicks on STOP button, clock will stop displaying time.
(Use Timer methods)
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Digital Clock</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
font-family: Arial, sans-serif;
}
#clock {
font-size: 2em;
margin: 20px;
}
button {
padding: 10px 20px;
font-size: 1em;
margin: 5px;
cursor: pointer;
}
</style>
</head>
<body>

<div id="clock">00:00:00</div>
<button id="startBtn">START</button>
<button id="stopBtn">STOP</button>

<script>
let timer; // To store the timer reference
const clockElement = document.getElementById('clock');
function startClock() {
// Start the timer
timer = setInterval(() => {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
clockElement.textContent = `${hours}:${minutes}:${seconds}`;
}, 1000);
}
function stopClock() {
// Stop the timer
clearInterval(timer);
}
document.getElementById('startBtn').addEventListener('click', startClock);
document.getElementById('stopBtn').addEventListener('click', stopClock);
</script>
</body>
</html>
(c) Write HTML code to design a form that displays textboxes for accepting UserID and
Aadhar No. and a SUBMIT button. UserID should contain 10 alphanumeric characters
and must start with Capital Letter. Aadhar No. should contain 12 digits in the format nnnn
nnnn nnnn. Write JavaScript code to validate the UserID and Aadhar No. when the user
clicks on SUBMIT button.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UserID and Aadhar Validation</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
}

.form-container {
max-width: 400px;
margin: auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

input[type="text"] {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 4px;
}

button {
width: 100%;
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
background-color: #007bff;
color: white;
font-size: 16px;
}

button:hover {
background-color: #0056b3;
}

.error {
color: red;
font-size: 14px;
margin-top: 10px;
}
</style>
</head>
<body>

<div class="form-container">
<h2>UserID and Aadhar Validation</h2>
<input type="text" id="userID" placeholder="Enter UserID (10 alphanumeric, start with
capital)" required>
<input type="text" id="aadharNo" placeholder="Enter Aadhar No. (12 digits, format: nnnn
nnnn nnnn)" required>
<button onclick="validateForm()">SUBMIT</button>
<div id="error-message" class="error"></div>
</div>

<script>
function validateForm() {
// Clear any previous error messages
document.getElementById("error-message").innerText = "";

// Get the values from the input fields


const userID = document.getElementById("userID").value;
const aadharNo = document.getElementById("aadharNo").value;

// Regular expression for UserID: must start with a capital letter and be 10 characters long
const userIDPattern = /^[A-Z][a-zA-Z0-9]{9}$/;
// Regular expression for Aadhar No: must be 12 digits and formatted as nnnn nnnn nnnn
const aadharPattern = /^\d{4} \d{4} \d{4}$/;

let errorMessage = "";

// Validate UserID
if (!userIDPattern.test(userID)) {
errorMessage += "Invalid UserID: Must start with a capital letter and be exactly 10
alphanumeric characters.\n";
}

// Validate Aadhar No.


if (!aadharPattern.test(aadharNo)) {
errorMessage += "Invalid Aadhar No.: Must be in the format nnnn nnnn nnnn (12
digits).\n";
}

// Display errors or success message


if (errorMessage) {
document.getElementById("error-message").innerText = errorMessage;
} else {
alert("Form submitted successfully!\nUserID: " + userID + "\nAadhar No.: " +
aadharNo);
}
}
</script>

</body>
</html>

6.Attempt any TWO of the following :

(a) Explain how to evaluate Radiobutton in JavaScript with suitable example.

Ans. In JavaScript, you can evaluate the selected value of a group of radio buttons by checking
which button is checked. Each radio button within a group has the same name attribute, which
allows the browser to treat them as a single selectable group.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Radio Button Evaluation Example</title>
</head>
<body>
<h2>Choose your favorite genre:</h2>
<form id="genreForm">
<label><input type="radio" name="genre" value="Rock"> Rock</label><br>
<label><input type="radio" name="genre" value="Pop"> Pop</label><br>
<label><input type="radio" name="genre" value="Jazz"> Jazz</label><br>
<label><input type="radio" name="genre" value="Classical"> Classical</label><br>
<button type="button" onclick="evaluateRadioButton()">Submit</button>
</form>
<p id="result"></p>
<script>
function evaluateRadioButton() {
// Get all radio buttons with the name 'genre'
const radioButtons = document.getElementsByName('genre');
let selectedValue = null;
// Loop through the radio buttons to find the selected one
for (const radioButton of radioButtons) {
if (radioButton.checked) {
selectedValue = radioButton.value;
break;
}
}
// Display the selected value or a message if none are selected
const resultElement = document.getElementById('result');
if (selectedValue) {
resultElement.textContent = `You selected: ${selectedValue}`;
} else {
resultElement.textContent = 'Please select a genre.';
}
}
</script>
</body>
</html>

(b) Explain how to evaluate Radiobutton in JavaScript with suitable example.


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 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.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Example</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
}
canvas {
border: 1px solid #ccc; /* Optional: border for the canvas */
}
</style>
</head>
<body>
<h1>Canvas Frame Structure</h1>
<script>
function createImage() {
const canvas = document.createElement('canvas');
canvas.width = 300;
canvas.height = 200;
const ctx = canvas.getContext('2d');
// Draw the outer rectangle
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
ctx.strokeRect(0, 0, canvas.width, canvas.height);
// Draw the horizontal line
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(canvas.width, 50);
ctx.stroke();
// Draw the vertical lines
ctx.beginPath();
ctx.moveTo(100, 0);
ctx.lineTo(100, canvas.height);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(200, 0);
ctx.lineTo(200, canvas.height);
ctx.stroke();
// Write the text
ctx.font = '16px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('FRAME 1', 150, 25);
ctx.fillText('SPORT', 50, 75);
ctx.fillText('MUSIC', 150, 75);
ctx.fillText('DANCE', 250, 75);
ctx.fillText('FRAME 2', 50, 150);
ctx.fillText('FRAME 3', 150, 150);
ctx.fillText('FRAME 4', 250, 150);
// Display the canvas
document.body.appendChild(canvas);
}
// Call the function to create the image
createImage();
</script>
</body>
</html>
(c) Write a JavaScript to create a pull – down menu with four options [AICTE, DTE,
MSBTE, GOOGLE]. Once the user will select one of the options then user will be
redirected to that site.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dropdown Menu Redirect</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
}
select {
padding: 10px;
font-size: 16px;
width: 200px;
}
button {
padding: 10px;
font-size: 16px;
margin-left: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<h2>Select a Site to Visit</h2>
<select id="siteSelector">
<option value="">-- Select a Site --</option>
<option value="https://www.aicte-india.org">AICTE</option>
<option value="https://dte.maharashtra.gov.in">DTE</option>
<option value="https://www.msbte.org.in">MSBTE</option>
<option value="https://www.google.com">GOOGLE</option>
</select>
<button onclick="redirectToSite()">Go</button>
<script>
function redirectToSite() {
const selector = document.getElementById("siteSelector");
const selectedValue = selector.value;
if (selectedValue) {
window.location.href = selectedValue; // Redirect to the selected site
} else {
alert("Please select a site to visit.");
}
}
</script>

</body>
</html>

You might also like