0% found this document useful (0 votes)
19 views

Css Ut2 Qb Solution

Uploaded by

Nishant Joshi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Css Ut2 Qb Solution

Uploaded by

Nishant Joshi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Unit Wise Question Bank for Unit Test – 2

Unit Question Marks


3 1. What is an intrinsic function? 2

 An intrinsic function is a function provided by the compiler to optimize code.


 Unlike regular functions, intrinsic functions are often built into the language to perform low-
level operations faster, as they may be replaced by specific machine instructions.
 Example:
let number = 16;
let sqroot = Math.sqrt(number); // Returns 4
console.log("The square root of", number, "is", sqroot);

3 2. Explain any two keyboard events in JavaScript. 2

 keydown Event
The keydown event is triggered when a key is pressed down. It fires continuously as long as the key
is held down, making it useful for detecting the start of a key press or repeating actions while the key
is held.
Example:
document.addEventListener("keydown", function(event) {
console.log("Key pressed: " + event.key); });
 keyup Event
The keyup event is triggered when a key is released. Unlike keydown, it only fires once per key
release, making it useful for finalizing actions or detecting the end of a key press.
Example:
document.addEventListener("keyup", function(event) {
console.log("Key released: " + event.key); });

3 3. What is the use of read-only element in JavaScript? 2

 A read-only element in JavaScript is used to display information in a form that users can view
but cannot modify.
 This is particularly useful for fields that need to show data without allowing any input or
alteration, such as calculated values, fixed information, or fields that should not be edited after
being set (like ID numbers or system-generated data).
3 4. Design a simple HTML form for filling the information for registration of a student. 4

<html >
<head>
<title>Student Registration Form</title>
</head>
<body>
<h2>Student Registration Form</h2>
<form id="registrationForm" onsubmit="showAlert(event)">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="course">Course:</label>
<input type="text" id="course" name="course" required><br><br>
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone" pattern="[0-9]{10}" placeholder="1234567890"
required><br><br>
<input type="submit" value="Register">
</form>
<script>
function showAlert(event) {
event.preventDefault(); // Prevents the form from submitting and refreshing the page
alert("Registration successful!");
}
</script>
</body>
</html>

3 5. Write a JavaScript to create three categories - Fruit, Flower and Colour. Based on the selection 4
of category, the item, in the option list must get changed.

<html >
<head>
<title>Dynamic Options </title>
</head>
<body>
<select id="category" onchange="updateOptions()">
<option value="fruit">Fruit</option>
<option value="flower">Flower</option>
<option value="color">Color</option>
</select>
<select id="items"></select>
<script>
const options = {
fruit: ["Apple", "Banana", "Cherry"],
flower: ["Rose", "Lily", "Daisy"],
color: ["Red", "Blue", "Green"]
};
function updateOptions() {
const category = document.getElementById("category").value;
const items = document.getElementById("items");
items.innerHTML = options[category].map(item => `<option>${item}</option>`).join('');
}
</script>
</body>
</html>

4 6. Explain the syntax for opening a window. 2

 A new browser window or tab can be opened using the window.open() method.
 This function provides a way to load a specific URL in a new window and offers options to
control the appearance and behavior of the window.
 Syntax:
window.open(URL, windowName, windowFeatures);
Parameters
 URL (optional): A string representing the URL to be loaded in the new window. If omitted or
set to "", a blank page will open.
 windowName (optional): A string specifying the name of the new window. This can be used
as a target in future calls to window.open().
 windowFeatures (optional): A comma-separated list of options specifying the features and
dimensions of the new window, such as width, height, left, top, resizable, scrollbars, toolbar,
location, status, menubar, etc.

4 7. Write a JavaScript to delete a cookie. 2

<html>
<body>
<script>
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
</script>
</body>
</html>

4 8. What are cookies? Explain how to create cookies in JavaScript. 4

 Cookies are small text files stored on a user's browser by websites to keep track of specific
information.
 They enable web applications to remember information about users, such as login details,
preferences, or tracking data.
 Cookies can be created directly in JavaScript by setting the ‘document.cookie’ property.
Here’s the basic syntax for creating a cookie:
document.cookie = "name=value; expires=expirationDate; path=path; domain=domain; secure;
samesite=sameSite";
Key Components
 name=value: The name and value of the cookie.
 expires: The expiration date (in UTC format). After this date, the cookie will be deleted.
 path: Specifies the URL path within which the cookie is accessible. The default path is the
current page.
 domain: Defines the domain for which the cookie is valid.
 secure: Ensures the cookie is only sent over HTTPS.
 samesite: Controls whether the cookie is sent with cross-site requests (values can be Strict,
Lax, or None).

Example:
<html>
<body>
<script>
function setCookie(name, value, days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); // days to milliseconds
let expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}
setCookie("username", "ABC", 7);
</script>
</body>
</html>

4 9. Explain how to set the expiration date of a cookie. 4

The expiration date of a cookie can be set using either the ‘expires’ attribute or the ‘max-age’ attribute.
Both specify when a cookie should be deleted, but they work slightly differently.

 Setting Expiration with expires


The expires attribute accepts a date string in UTC format and sets the exact date and time when the
cookie should expire. Once that date is reached, the browser will automatically delete the cookie.
Format: expires=Thu, 01 Jan 1970 00:00:00 UTC
Example:
function setCookieWithExpires(name, value, days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); // days to milliseconds
let expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}
setCookieWithExpires("username", "ABC", 7);

 Setting Expiration with max-age


The max-age attribute specifies the lifespan of a cookie in seconds, starting from the time it is set.
When the max-age time elapses, the cookie will automatically expire and be deleted by the browser.
Format: max-age=seconds

Example:
function setCookieWithMaxAge(name, value, days) {
let maxAge = days * 24 * 60 * 60; // days to seconds
document.cookie = name + "=" + value + "; max-age=" + maxAge + "; path=/";
}
// Set a cookie with name "username" that expires in 7 days
setCookieWithMaxAge("username", "Alice", 7);

4 10. What is the use of setInterval() and setTimeout() function? Write a JavaScript to illustrate both. 4

The setInterval() and setTimeout() functions in JavaScript are used to execute code after a delay.
However, they operate differently in terms of timing and repetition.

 setTimeout()
The setTimeout() function is used to execute a specified function or code snippet after a specified
delay, measured in milliseconds. It only runs the code once, after the delay has passed.
Syntax: setTimeout(function, delay, arg1, arg2, ...);
function: The function or code snippet to execute after the delay.
delay: The delay in milliseconds before the function runs (1 second = 1000 milliseconds).
arg1, arg2,.. : Optional arguments to pass to the function being called.

Example:
setTimeout(() => {
console.log("This message is displayed after 3 seconds.");
}, 3000); //This example will log a message to the console after 3 seconds.

 setInterval()
The setInterval() function is used to repeatedly execute a specified function or code snippet at a fixed
interval, measured in milliseconds. It continues to run the code at the interval until it's stopped (with
clearInterval()).
Syntax: setInterval(function, interval, arg1, arg2, ...);
function: The function or code snippet to execute.
interval: The interval (in milliseconds) between each execution.
arg1, arg2, ...: Optional arguments to pass to the function being called.

Example:
setInterval(() => {
console.log("This message is displayed every 2 seconds.");
}, 2000); //This example logs a message to the console every 2 seconds, until it’s stopped.

JavaScript Code Example to Illustrate Both


<html>
<head>
<title>setTimeout and setInterval Example</title>
</head>
<body>
<button onclick="startInterval()">Start Interval</button>
<button onclick="stopInterval()">Stop Interval</button>
<div id="timeoutMessage"></div>
<div id="intervalMessage"></div>
<script>
// Using setTimeout to display a one-time message after 5 seconds
setTimeout(() => {
document.getElementById("timeoutMessage").innerText = "This message appears after 5
seconds!";
}, 5000); // Delay of 5 seconds
// Using setInterval to display a message every 3 seconds
let intervalId;
function startInterval() {
intervalId = setInterval(() => {
let now = new Date().toLocaleTimeString();
document.getElementById("intervalMessage").innerText = "This message updates every 3
seconds. Current time: " + now;
}, 3000); // Interval of 3 seconds
}
// Function to stop the setInterval
function stopInterval() {
clearInterval(intervalId);
document.getElementById("intervalMessage").innerText = "Interval stopped.";
}
</script>
</body>
</html>

5 11. Define the term – Regular expression. 2

A Regular Expression (often abbreviated as regex or regexp) is a sequence of characters that defines
a search pattern. Regular expressions are used for pattern matching within strings and are commonly
employed in programming for text processing tasks, such as searching, matching, and replacing text.

Syntax: let regex = /pattern/flags;

Key Uses of Regular Expressions:


 Validation: Ensuring inputs meet specific formats (e.g., emails, phone numbers).
 Search: Finding specific patterns within text (e.g., locating all instances of a word).
 Replace: Modifying matched patterns within text (e.g., replacing old dates with new ones).
 Parsing: Extracting data based on complex patterns.

5 12. Construct regular expression for validating the phone number in following format only: (nnn)- 2
nnnn-nnnn OR nnn.nnnn.nnnn

/^\(?\d{3}\)?[-.]?\d{4}[-.]\d{4}$/

Explanation of the Regular Expression:


 ^ : Ensures the pattern starts from the beginning of the string.
 \(?\d{3}\)? :
 \(?: Matches an optional opening parenthesis (.
 \d{3}: Matches exactly three digits.
 \)?: Matches an optional closing parenthesis ).
 [-.]?: Matches an optional dash - or period . after the first set of digits.
 \d{4}: Matches exactly four digits (the next segment of the phone number).
 [-.]: Matches either a dash - or period . as a separator between the segments.
 \d{4}: Matches the last four digits.
 $ : Ensures the pattern ends at the end of the string.

5 13. Explain frameset tag along with the attributes used in it. 4

 The <frameset> tag in HTML is used to define a collection of frames within a browser window.
 It is often used in place of the <body> tag when designing a web page layout that requires
splitting the browser window into multiple, scrollable sections, each displaying a separate
HTML document.
 The <frameset> element holds multiple <frame> elements, each specifying a source URL for
the content displayed in that section of the frameset.
 The browser window is divided horizontally or vertically using the rows or cols attributes of
the <frameset> tag.
<!DOCTYPE html>
<html>
<head>
<title>Frameset Example</title>
</head>
<frameset rows="50%,50%">
<frame src="header.html" name="header">
<frameset cols="50%,50%">
<frame src="content.html" name="content">
<frame src="sidebar.html" name="sidebar">
</frameset>
</frameset>
</html>

Attributes of <frameset>
 rows and cols:
rows: Defines the number and size of rows in the frameset. Each row height is specified in the attribute
value as a comma-separated list (e.g., "50%,50%" divides the space into two rows of equal height).
cols: Defines the number and size of columns in the frameset. Each column width is specified in the
attribute value as a comma-separated list (e.g., "25%,50%,25%" creates three columns with specified
widths).
Units:
Percentages (%): Relative to the total available width or height.
Pixels (px): Fixed pixel width/height.
Asterisk (*): Indicates a flexible size that adjusts to fill remaining space.
 frameborder:
Controls whether borders appear between frames. Set to "1" to display borders or "0" to hide them.

 border:
Sets the thickness of the frame borders. Specified in pixels.

 framespacing:
Defines the amount of space, in pixels, between frames.

 noresize:
Prevents the frame from being resized by the user. This attribute is added to the <frame> element.

 Nested <frameset>:
<frameset> elements can be nested to create complex grid layouts of rows and columns.

5 14. What is frame? Write a JavaScript to display frames without border. 4

 A frame in HTML refers to a section of the browser window that can load and display a
separate HTML document.
 Frames are often used in conjunction with the <frameset> tag to split the browser window into
multiple, independently scrollable regions, each capable of displaying different content or
webpages.

Displaying Frames without Borders


To display frames without borders, you can set the frameborder attribute of the <frame> elements to
"0" (zero) or use the border attribute on the <frameset> tag.

<html>
<head>
<title>Frames Without Borders</title>
</head>
<body>
<frameset rows="50%,50%" frameborder="0" border="0" framespacing="0">
<frame src="topFrame.html" name="topFrame" frameborder="0" noresize>
<frame src="bottomFrame.html" name="bottomFrame" frameborder="0" noresize>
</frameset>
</body>
</html>

5 15. Write a JavaScript program to create rollover effect for three images. 4

<html>
<head>
<title>Image Rollover Effect</title>
</head>
<body>

<!-- Define three images with unique IDs and set the initial image sources -->
<img src="image1.jpg" id="img1" width="200" height="150" onmouseover="rollover('img1',
'image1-hover.jpg')" onmouseout="rollout('img1', 'image1.jpg')">
<img src="image2.jpg" id="img2" width="200" height="150" onmouseover="rollover('img2',
'image2-hover.jpg')" onmouseout="rollout('img2', 'image2.jpg')">
<img src="image3.jpg" id="img3" width="200" height="150" onmouseover="rollover('img3',
'image3-hover.jpg')" onmouseout="rollout('img3', 'image3.jpg')">
<script>
// Function to change the image on mouseover
function rollover(imageId, hoverSrc) {
document.getElementById(imageId).src = hoverSrc;
}
// Function to revert back to the original image on mouseout
function rollout(imageId, originalSrc) {
document.getElementById(imageId).src = originalSrc;
}
</script>
</body>
</html>
6 16. What is slide show? 2

 In JavaScript, a slideshow is a technique used to display a sequence of images or other content


in a cycle, either automatically at regular intervals or manually when the user interacts with
the slideshow controls (e.g., "Next" or "Previous" buttons).
 Slideshows are commonly used for image galleries, presentations, and advertisements on
websites.
 They can enhance user engagement by presenting content in a visually appealing and
interactive way.
 Basic Components of a JavaScript Slideshow
o Image Array or Collection: A list of images or content items to display in the slideshow,
which can be hardcoded or dynamically generated.
o Current Slide Index: Tracks the currently displayed slide in the array, allowing
navigation through the slides.
o Navigation Controls:
 Next and Previous buttons allow users to manually navigate the slideshow.
 Play/Pause button for automatic playback.
o Timing Control (Optional):
 Using JavaScript functions like setInterval() to automate the slideshow by
changing slides at regular intervals.

6 17. What is banner ad? 2

A banner ad is a form of online advertising that involves displaying a graphical advertisement on a


webpage. These ads are typically rectangular and are placed in high-visibility areas, such as at the
top, bottom, or sides of a webpage. The primary purpose of banner ads is to attract traffic to a
website by linking to the advertiser's site when clicked. In the context of JavaScript, banner ads can
be dynamically managed and manipulated, providing more interactive and engaging experiences for
users.

Key Components of Banner Ads

1. Visual Elements: Banner ads can include images, text, animations, and interactive elements
(like buttons or forms) to capture user attention.
2. Click-Through Action: When a user clicks on the banner ad, they are redirected to the
advertiser's website, landing page, or specific content.
3. Tracking and Analytics: Advertisers often implement tracking to measure the performance
of banner ads, including impressions (how many times the ad is shown), clicks, and
conversions.
4. Responsive Design: Many banner ads are designed to be responsive, meaning they adapt to
different screen sizes and devices, enhancing user experience across platforms.

6 18. Write a JavaScript to create and display a banner. 4

<html>
<head>
<title>Simple Banner Ad</title>
<style>
#banner-ad {
width: 600px;
height: 250px;
background-color: #f4f4f4;
border: 2px solid #ccc;
position: relative;
margin: auto;
overflow: hidden;
}
#banner-image {
width: 100%;
height: 100%;
transition: opacity 0.5s ease;
}
#banner-text {
position: absolute;
bottom: 10px;
left: 10px;
color: #fff;
background-color: rgba(0, 0, 0, 0.7);
padding: 10px;
}
#clickable {
position: absolute;
width: 100%;
height: 100%;
cursor: pointer;
}
</style>
</head>
<body>

<div id="banner-ad">
<img src="banner1.jpg" id="banner-image" alt="Banner Ad">
<div id="banner-text">Click here for special offers!</div>
<a href="https://www.example.com" target="_blank" id="clickable"></a>
</div>

<script>
const bannerImages = [
'banner1.jpg',
'banner2.jpg',
'banner3.jpg'
];
let currentImageIndex = 0;

function changeBannerImage() {
currentImageIndex = (currentImageIndex + 1) % bannerImages.length;
const bannerImage = document.getElementById('banner-image');
bannerImage.style.opacity = 0; // Fade out
setTimeout(() => {
bannerImage.src = bannerImages[currentImageIndex];
bannerImage.style.opacity = 1; // Fade in
}, 500); // Delay for fade out transition
}

// Change the banner image every 5 seconds


setInterval(changeBannerImage, 5000);
</script>

</body>
</html>
6 19. What is a menu? List all types of menus and explain any 1 with example. 4

In JavaScript, a menu refers to a navigational component on a webpage that allows users to select
options, access different parts of the site, or perform specific actions. Menus can come in various
forms and styles, often enhancing user experience by providing a structured way to access content or
functionalities. Menus can be static or dynamic, and they can include dropdowns, pop-ups, sidebars,
and more.

Types of Menus in JavaScript

1. Dropdown Menu: A menu that expands to show sub-options when hovered over or clicked.
2. Context Menu: A menu that appears when a user right-clicks on an element, offering
contextual actions.
3. Tab Menu: A menu that displays content in tabs, allowing users to switch between different
sections without reloading the page.
4. Sidebar Menu: A vertical menu that usually appears on the side of a webpage, providing
navigation links.
5. Sliding Menu: A menu that slides in and out from the side of the screen, often used in
mobile designs.
6. Accordion Menu: A vertically stacked list of items where each item can be expanded or
collapsed to show more options.
7. Mega Menu: A large dropdown menu that can display multiple categories and
subcategories, often used in e-commerce websites.

Explanation of Two Types of Menus with Examples


1. Dropdown Menu

A dropdown menu allows users to hover over or click an item to reveal a list of related links or
options. Dropdown menus are commonly used in navigation bars.

<html>
<head>
<title>Dropdown Menu</title>
<style>
.navbar { background-color: #333; overflow: hidden; }
.navbar a, .dropbtn { color: white; padding: 14px 16px; text-decoration: none; }
.dropdown { float: left; position: relative; }
.dropdown-content {
display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; z-index: 1;
}
.dropdown:hover .dropdown-content { display: block; }
</style>
</head>
<body>

<div class="navbar">
<a href="#home">Home</a>
<div class="dropdown">
<button class="dropbtn">Services</button>
<div class="dropdown-content">
<a href="#service1">Service 1</a>
<a href="#service2">Service 2</a>
</div>
</div>
<a href="#about">About</a>
</div>

</body>
</html>
6 20. Write short note on - Frameworks of JavaScript and applications. 4

Frameworks of JavaScript and its Application


 A JavaScript framework is a collection of JavaScript code libraries that provide a web
developer with pre-written code for routine programming tasks.
 Frameworks are structures with a particular context and help you create web applications
within that context.
 It is completely possible to build strong web applications without JavaScript frameworks, but
frameworks provide a template that handles common programming patterns.
 Each time you have to build an application, you don’t need to write code for every single
feature from scratch. Instead, you can build upon an existing feature set.
 All JavaScript frameworks, like most other frameworks, provide some rules and guidelines.
 Using these rules and guidelines, any developer can make complex applications faster and
more efficiently than if they decided to build from scratch.
 Following are the javascript frameworks with their applications:

1) ReactJs
React is based on a reusable component. Simply put, these are code blocks that can be classified as
either classes or functions. Each component represents a specific part of a page, such as a logo, a
button, or an input box. The parameters they use are called props, which stands for properties.
Applications:
React is a JavaScript library developed by Facebook which, among other things, was used to build
Instagram.com.

2) Angular
Google operates this framework and is designed to use it to develop a Single Page Application (SPA).
This development framework is known primarily because it gives developers the best conditions to
combine JavaScript with HTML and CSS. Google operates this framework and is designed to use it
to develop a Single Page Application (SPA). This development framework is known primarily because
it gives developers the best conditions to combine JavaScript with HTML and CSS.
Applications:
Microsoft Office ,Gmail, Forbes, PayPal, Grasshopper, Samsung, Delta

3) Vue.js
Vue is an open-source JavaScript framework for creating a creative UI. The integration with Vue in
projects using other JavaScript libraries is simplified because it is designed to be adaptable.
Application:
VueJS is primarily used to build web interfaces and one-page applications. It can also be applied to
both desktop and mobile app development.

4) jQuery
It is a cross-platform JavaScript library designed to simplify HTML client-side scripting. You can use
the jQuery API to handle, animate, and manipulate an event in an HTML document, also known as
DOM. Also, jQuery is used with Angular and React App building tools.
Applications:
 JQuery can be used to develop Ajax based applications.
 It can be used to make code simple, concise and reusable.
 It simplifies the process of traversal of HTML DOM tree.
 It can also handle events, perform animation and add ajax support in web applications.

5) Node.js
Node.js is an open-source, server-side platform built on the Google Chrome JavaScript Engine.
Node.js is an asynchronous, single-threaded, non-blocking I/O model that makes it lightweight and
efficient.
Applications:
Paypal, LinkedIn, Yahoo, Mozilla, Netflix, Uber, Groupon, GoDaddy, eBay

You might also like