Css Ut2 Qb Solution
Css Ut2 Qb Solution
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); });
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>
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.
<html>
<body>
<script>
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
</script>
</body>
</html>
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>
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.
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.
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.
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}$/
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.
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.
<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
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.
<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
}
</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.
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.
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
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