CSS Finals QB (WITH ANSWERS)
CSS Finals QB (WITH ANSWERS)
CSS Finals QB (WITH ANSWERS)
Unit 1:
Theory:
Q1) Features of JS. 2M
JavaScript (JS) is a versatile programming language that is primarily used for front-end web development but
can also be employed on the server-side. Here are some key features of JavaScript:
1. Client-Side Scripting
2. Cross-platform Compatibility
3. Asynchronous Programming
4. Object-Oriented
5. Dynamic Typing
6. Prototype-based Inheritance
7. Event-Driven Programming
8. Libraries and Frameworks
Q2) CSS (Client-Side Scripting) VS SSS (Server-Side Scripting). (Write any 2 – 4npoints) 2M
Feature CSS (Client-Side Scripting) SSS (Server-Side Scripting)
Execution Location Runs on the client's browser. Executes on the server.
Responsibility Primarily handles the Manages server-side logic, data processing,
presentation and styling of and business logic.
web content.
Access to DOM Can manipulate the Typically, does not directly manipulate the
Document Object Model client-side DOM.
(DOM) on the client side.
User Interaction Can respond to user Limited ability to respond to user interactions
interactions in real-time. without additional technologies like AJAX.
Performance Impact Affects client-side rendering Server-side processing can affect response
and can impact page load times for dynamic content.
times.
Code Visibility Code is visible to users and Server-side code is not visible to users.
can be inspected using
browser tools.
Security Limited security measures as Server-side code is secure as it runs on the
Considerations code is accessible to users. server and is not exposed to users.
Browser Compatibility CSS is supported by all Server-side scripting languages may have
major browsers. variations in support across servers, but the
output (HTML, CSS, etc.) is generally browser-
compatible.
Examples <style> tags in HTML, PHP, Python (Django), Ruby (Ruby on Rails),
external CSS files. Node.js, ASP.NET.
Common Use Cases Styling web pages, creating Handling form submissions, database
responsive designs. interactions, dynamic content generation.
Frameworks/Libraries No specific frameworks, but Numerous frameworks like Django (Python),
may use CSS preprocessors Express (Node.js), Ruby on Rails (Ruby), etc.
like Sass.
File Extensions Typically uses .css file Depends on the server-side scripting
extensions. language; for example, .php, .py, .rb, .js
(Node.js).
Q3) Advantage & Disadvantage of JS. (Write any 2 – 4 points from both) 2M
1. Versatility: JavaScript is a versatile language that can be used for both client-side and server-side
development, making it a key technology for full-stack development.
2. Interactivity: JavaScript enhances user interactivity on websites by allowing the creation of dynamic
and responsive user interfaces. It can handle events such as clicks, keypresses, and form submissions.
3. Asynchronous Programming: JavaScript supports asynchronous programming, enabling the execution
of non-blocking code. This is crucial for handling tasks such as fetching data from servers without freezing
the user interface.
4. Large Ecosystem: JavaScript has a vast ecosystem with numerous libraries (e.g., jQuery, React, Vue.js)
and frameworks (e.g., Node.js) that simplify development and promote code reusability.
5. Community Support: JavaScript has a large and active community of developers, which means there
is a wealth of resources, tutorials, and third-party libraries available for support.
6. Cross-Browser Compatibility: JavaScript is supported by all major web browsers, ensuring that scripts
can run consistently across different platforms.
7. Easy to Learn: JavaScript has a relatively simple and straightforward syntax, making it accessible for
beginners. It's an excellent language for those new to programming.
8. Integration with HTML and CSS: JavaScript seamlessly integrates with HTML and CSS, allowing
developers to create dynamic and visually appealing web pages.
Disadvantages of JavaScript:
1. Security Concerns: Because JavaScript code is executed on the client-side, it is visible to users. This can
expose security vulnerabilities, and developers must take precautions to secure their code.
2. Browser Dependency: Despite efforts to standardize, there may be variations in how different
browsers interpret and execute JavaScript. Developers need to be mindful of cross-browser
compatibility issues.
3. Limited Storage: JavaScript has limited storage capabilities on the client side. This can be a constraint
when dealing with large amounts of data or when attempting to store data persistently.
4. Single-threaded Execution: JavaScript is single-threaded, meaning it can only execute one task at a
time. While asynchronous programming mitigates this to some extent, heavy computations can still
impact performance.
5. No Multithreading: JavaScript lacks native support for multithreading, which can be a limitation when
dealing with complex and resource-intensive applications.
6. Dependency on Client-Side Processing: Heavy reliance on client-side processing can lead to slower
performance, especially on devices with limited resources.
7. SEO Challenges: Search engine optimization (SEO) can be challenging with purely client-side-rendered
applications, as search engines may have difficulty crawling and indexing content.
8. No File System Access: For security reasons, JavaScript does not have direct access to a user's file
system. This can limit certain functionalities, such as file manipulation tasks.
/*
This is a
multi-line comment
*/
2. Variables:
• Variables are used to store and manage data in a program.
• They are declared using the var, let, or const keyword.
var message = "Hello, World!";
let count = 5;
const PI = 3.14;
3. Data Types:
• JavaScript supports various data types, including strings, numbers, booleans, objects, arrays, and more.
var name = "John";
var age = 25;
var isStudent = true;
var person = { firstName: "John", lastName: "Doe" };
var numbers = [1, 2, 3, 4, 5];
4. Functions:
• Functions in JavaScript are blocks of reusable code.
• They are defined using the function keyword.
function greet(name) {
return "Hello, " + name + "!";
}
5. Control Structures:
• Control structures like if, else, for, while, etc., are used to control the flow of the program.
var score = 85;
6. Loops:
• Loops are used to repeatedly execute a block of code.
• Common loops include for, while, and do-while.
for (var i = 0; i < 5; i++) {
console.log(i);
}
7. Events:
• In web development, JavaScript often interacts with events triggered by user actions (e.g., clicks,
keypresses).
• Event handlers are functions that respond to these events.
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
8. Output:
• The console.log() function is commonly used to output information to the browser console during
development.
console.log("This is a log message");
7. Array:
A special type of object that stores a list of values.
•
Example: var numbers = [1, 2, 3, 4, 5];
•
8. Symbol:
• Introduced in ECMAScript 6 (ES6), symbols are unique and immutable data types, often used as
identifiers for object properties.
var mySymbol = Symbol("mySymbol");
9. BigInt:
• Introduced in ECMAScript 2020, BigInt is used to represent integers of arbitrary precision.
var bigNumber = 1234567890123456789012345678901234567890n;
Q7) Define Object name, Property, Method, Dot syntax, Main event. 4M
Object name: In JavaScript, an "object name" typically refers to the name or identifier used to reference an object.
Objects are variables that can contain data and functions, and they are defined using a name or identifier.
Property: A property in JavaScript is a key-value pair associated with an object. It represents a characteristic or attribute
of the object and can store data.
Method: A method in JavaScript is a function that is associated with an object. It defines the behaviour or actions that can
be performed on or with the object.
Dot Syntax: The dot syntax in JavaScript is a way to access properties and methods of an object. It involves using a ‘.’ to
connect the object and the property or method you want to access.
Main Event: Events are actions or occurrences in the browser, such as user interactions (clicks, keypresses) or changes in the
document (load, resize).
Operators: Comparison operators in JavaScript are used to compare two values and return a Boolean result. Common
comparison operators include:
• Equal (==): Returns true if the values are equal, and false otherwise. Example: a == b
• Not Equal (!=): Returns true if the values are not equal, and false otherwise. Example: a != b
• Strict Equal (===): Returns true if the values are equal and of the same type, and false otherwise.
Example: a === b
• Strict Not Equal (!==): Returns true if the values are not equal or not of the same type, and false
otherwise. Example: a !== b
• Greater Than (>), Less Than (<): Compare whether one value is greater than or less than another,
respectively. Example: a > b, a < b
• Greater Than or Equal To (>=), Less Than or Equal To (<=): Check if one value is greater than or
equal to, or less than or equal to another. Example: a >= b, a <= b
b. Logical Operators: Logical operators in JavaScript are used to perform logical operations on boolean
values. Common logical operators include:
• Logical AND (&&): Returns true if both operands are true. Example: a && b
• Logical OR (||): Returns true if at least one operand is true. Example: a || b
• Logical NOT (!): Returns true if the operand is false, and vice versa. Example: !a
c. Bitwise Operators: Bitwise operators perform operations on the binary representations of integer values.
Common bitwise operators include:
• Bitwise AND (&): Performs a bitwise AND operation.
• Bitwise OR (|): Performs a bitwise OR operation.
• Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation.
• Bitwise NOT (~): Inverts the bits of its operand.
• Left Shift (<<): Shifts the bits of the left operand to the left by a specified number of positions.
• Right Shift (>>): Shifts the bits of the left operand to the right by a specified number of positions.
d. Conditional (Ternary) Operator: The conditional operator, often called the ternary operator, is a shorthand
way to write an if-else statement. It has the following syntax:
condition ? expression_if_true : expression_if_false;
It evaluates the condition, and if the condition is true, it returns the result of expression_if_true; otherwise, it
returns the result of expression_if_false. Example: a > b ? "a is greater" : "b is greater"
b. alert() Method:
• The alert() method displays a dialog box with a specified message and an "OK" button.
• It is commonly used for providing information or notifications to the user.
Example:
alert("This is an alert message!");
c. confirm() Method:
• The confirm() method displays a dialog box with a specified message, along with "OK" and "Cancel"
buttons.
• It is often used to get a binary response from the user, where the result is either true (OK) or false
(Cancel).
Example:
let userResponse = confirm("Do you want to proceed?");
if (userResponse) {
console.log("User clicked OK");
} else {
console.log("User clicked Cancel");
}
console() Object:
• The console object in JavaScript provides methods for logging information to the browser's console. It
is mainly used for debugging and monitoring.
Example:
console.log("This is a log message");
console.warn("This is a warning message");
console.error("This is an error message");
Q2) Armstrong
function isArmstrong(number) {
const numDigits = String(number).length;
let sum = 0;
let temp = number;
while (temp > 0) {
const digit = temp % 10;
sum += Math.pow(digit, numDigits);
temp = Math.floor(temp / 10);
}
Q5) WJSP That computes AVG marks of 5 students/following students. Then use AVG to determine
their corresponding grades.
function calculateAverage(marks) {
const totalMarks = marks.reduce((sum, mark) => sum + mark, 0);
return totalMarks / marks.length;
}
function determineGrade(avg) {
if (avg >= 90) {
return 'A';
} else if (avg >= 80) {
return 'B';
} else if (avg >= 70) {
return 'C';
} else if (avg >= 60) {
return 'D';
} else {
return 'F';
}
}
const studentMarks = [85, 92, 78, 88, 95]; // Replace with the marks of the students
const average = calculateAverage(studentMarks);
const grade = determineGrade(average);
Example:
// Defining an array of numbers
const numericArray = [1, 2, 3, 4, 5];
pop():
• Purpose: Removes the last element from an array and returns that element.
• Usage Example: const removedElement = array.pop();
push():
• Purpose: Adds one or more elements to the end of an array and returns the new length of the array.
• Usage Example: const newLength = array.push(element1, element2);
indexOf():
• Purpose: Returns the first index at which a specified element is found in an array. If the element is not
present, it returns -1.
• Usage Example: const index = array.indexOf(searchElement);
reverse():
• Purpose: Reverses the order of the elements in an array.
• Usage Example: array.reverse();
unshift():
• Purpose: Adds one or more elements to the beginning of an array and returns the new length of the
array.
• Usage Example: const newLength = array.unshift(element1, element2);
charAt():
• Purpose: Returns the character at the specified index in a string.
• Usage Example: const character = str.charAt(index);
shift():
• Purpose: Removes the first element from an array and returns that element.
• Usage Example: const removedElement = array.shift();
Function Expression:
Syntax:
const functionName = function(parameters) {
// function body
};
Example:
const greet = function(name) {
console.log(`Hello, ${name}!`);
};
greet("Bob");
Recursive Function:
Example:
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorial(n - 1);
}
Generator Function:
Syntax:
function* functionName(parameters) {
// function body
}
Example:
function* generateNumbers() {
yield 1;
yield 2;
yield 3;
}
Function Name:
A name that identifies the function. It must be a valid JavaScript identifier.
function greet(name) {
// function body
}
Parameters:
Variables listed inside the parentheses in the function declaration. They act as placeholders for values that will
be passed to the function when it is called.
function addNumbers(a, b) {
// function body
}
Function Body:
The block of code enclosed in curly braces {}. It contains the statements that define what the function does.
function multiply(a, b) {
const result = a * b;
return result;
}
Return Statement:
The return statement specifies the value that the function should return when it is called. A function may not have
a return statement, in which case it returns undefined.
function square(x) {
return x * x;
}
Function Call:
To execute a function, you need to call it by using its name followed by parentheses. If the function has
parameters, you pass values inside these parentheses.
const result = addNumbers(3, 4);
// Function Call
const powerResult = calculatePower(2, 3);
console.log(powerResult); // Output: 8
toUpperCase():
• Purpose: Converts all characters in a string to uppercase.
• Example:
• const str = "Hello";
• const upperCaseStr = str.toUpperCase(); // Returns "HELLO"
toLowerCase():
• Purpose: Converts all characters in a string to lowercase.
• Example:
• const str = "Hello";
• const lowerCaseStr = str.toLowerCase(); // Returns "hello"
substring():
• Purpose: Returns a portion of a string between two specified indices.
• Example:
• const str = "Hello World";
• const subStr = str.substring(0, 5); // Returns "Hello"
substr():
• Purpose: Returns a portion of a string, starting from a specified index for a specified number of
characters.
• Example:
• const str = "Hello World";
• const subStr = str.substr(6, 5); // Returns "World"
replace():
• Purpose: Replaces a specified substring or pattern with another string.
• Example:
• const str = "Hello World";
• const newStr = str.replace("World", "Universe"); // Returns "Hello Universe"
split():
• Purpose: Splits a string into an array of substrings based on a specified separator.
• Example:
• const str = "apple,orange,banana";
• const fruitsArray = str.split(","); // Returns ["apple", "orange", "banana"]
valueOf():
• Purpose: Returns the primitive value of a string object.
• Example:
• const strObject = new String("Hello");
• const primitiveValue = strObject.valueOf(); // Returns "Hello"
slice():
• Purpose: Extracts a portion of a string and returns it as a new string, without modifying the original
string.
• Example:
• const str = "Hello World";
• const slicedStr = str.slice(6); // Returns "World"
console.log(separatedArray);
// Output: ["apple", "orange", "banana"]
Programs:
Q1) WJSP to display 5 elements of array & sort them in any order using array function. 4M
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sort Array</title>
<script>
window.onload = function() {
const numbers = [5, 2, 8, 1, 4];
// Display elements
console.log("Original Array:", numbers);
Q2) WJSP that initialize an array called fruits with the names of 3 fruits. 2M
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fruits Array</title>
<script>
window.onload = function() {
// Initialize an array called fruits
const fruits = ["Apple", "Banana", "Orange"];
return character;
}
// Example usage:
const inputString = "Hello, World!";
const position = 7;
<script>
document.getElementById('myDiv').addEventListener('dblclick', function() {
alert('Div double-clicked!');
});
</script>
</body>
</html>
• Double-Click Event:
o The dblclick event occurs when the user double-clicks the left mouse button.
<!DOCTYPE html>
<html>
<head>
<title>Double-Click Event Example</title>
</head>
<body>
<div id="myDiv">Double-click me</div>
<script>
document.getElementById('myDiv').addEventListener('dblclick', function() {
alert('Div double-clicked!');
});
</script>
</body>
</html>
<script>
const myElement = document.getElementById('myElement');
myElement.addEventListener('mouseover', function() {
this.style.backgroundColor = 'lightblue';
});
myElement.addEventListener('mouseout', function() {
this.style.backgroundColor = '';
});
</script>
</body>
</html>
<script>
document.getElementById('myDiv').addEventListener('mousemove', function(event) {
console.log(`Mouse coordinates: (${event.clientX}, ${event.clientY})`);
});
</script>
</body>
</html>
<script>
document.getElementById('myInput').addEventListener('keydown', function(event) {
alert(`Key pressed: ${event.key}`);
});
</script>
</body>
</html>
Keyup Event:
• The keyup event occurs when a key on the keyboard is released.
<!DOCTYPE html>
<html>
<head>
<title>Keyup Event Example</title>
</head>
<body>
<input type="text" id="myInput" placeholder="Release a key">
<script>
document.getElementById('myInput').addEventListener('keyup', function(event) {
alert(`Key released: ${event.key}`);
});
</script>
</body>
</html>
Keypress Event:
• The keypress event occurs when a key that produces a character value is pressed down.
<!DOCTYPE html>
<html>
<head>
<title>Keypress Event Example</title>
</head>
<body>
<input type="text" id="myInput" placeholder="Press a key with character">
<script>
document.getElementById('myInput').addEventListener('keypress', function(event) {
alert(`Character pressed: ${String.fromCharCode(event.charCode)}`);
});
</script>
</body>
</html>
isNaN():
• The isNaN() function checks whether a value is NaN (Not a Number) or not.
let result = isNaN("Hello");
Programs:
Q1) WJSP to design a form to accept values for UID and Password. 2M
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Login Form</title>
</head>
<body>
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="Enter your
Password" required>
</body>
</html>
Q2) WHTML script which displays 2 radio buttons for fruits abd vegetables & one option list. When a
user selects fruits then option list should present only fruits & if vegetables that display only vegetables
(changing option list dynamically). 6M
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fruits and Vegetables Selector</title>
</head>
<body>
<form>
<label>
<input type="radio" name="category" value="fruits" onclick="updateOptions()">
Fruits
</label>
<label>
<input type="radio" name="category" value="vegetables"
onclick="updateOptions()"> Vegetables
</label>
<br>
<script>
function updateOptions() {
var foodList = document.getElementById('foodList');
var category = document.querySelector('input[name="category"]:checked').value;
</body>
</html>
Q3) WJSP that displays text boxes for accepting name email ID, password & a submit button write a
code such that when a user clicks on submit button: 6M
a. Name Validation
b. Email Validation
c. Password Validation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration Form</title>
</head>
<body>
<form id="registrationForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your name" required>
<div id="nameError" class="error-message"></div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email"
required>
<div id="emailError" class="error-message"></div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="Enter your
password" required>
<div id="passwordError" class="error-message"></div>
<script>
function validateForm() {
// Reset error messages
document.getElementById('nameError').innerText = '';
document.getElementById('emailError').innerText = '';
document.getElementById('passwordError').innerText = '';
// Get form values
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
// Email validation
var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
document.getElementById('emailError').innerText = 'Invalid email address';
return false;
}
</body>
</html>
<head>
<title>
HTML forms
</title>
<script>
function selection() {
var x = "You selected:";
with (document.forms.myform) {
if (a.checked == true) {
x += a.value;
}
if (b.checked == true) {
x += b.value;
}
if (o.checked == true) {
x += o.value;
}
if (p.checked == true) {
x += p.value;
}
if (g.checked == true) {
x += g.value;
}
}
}
</script>
</head>
<body>
<form name="myform" method="post">
Select your favorite food <br>
<input type="checkbox" value="Apple">Apple
<input type="checkbox" value="Banan">Banan
<input type="checkbox" value="Orange">Orange
<input type="checkbox" value="Pear">Pear
<input type="checkbox" value="Grapes">Grapes
<input type="reset" value="Show" onclick="selection()"
</form>
</body>
</html>
<head>
<title>How to get value of selected radio button using JavaScript?</title>
</head>
<body>
<p>
Select a radio button and click on Submit.
</p>
Gender:
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Others">Others
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
<div id="result"></div>
<script>
function displayRadioValue() {
var ele = document.getElementsByName('gender');
for (i = 0; i < ele.length; i++) {
if (ele[i].checked)
document.getElementById("result").innerHTML
= "Gender: " + ele[i].value;
}
}
</script>
</body>
</html>
Q6) WJSP to performance arithmetic operation of 2 Numbers. Construct that contains 2 textbox and 4
buttons for add, sub, mul, div. 4M
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arithmetic Operations</title>
</head>
<body>
<h2>Arithmetic Operations</h2>
<br>
<br>
<label for="result">Result:</label>
<input type="text" id="result" readonly>
<script>
function performOperation(operation) {
var num1 = parseFloat(document.getElementById('num1').value);
var num2 = parseFloat(document.getElementById('num2').value);
switch (operation) {
case 'add':
result = num1 + num2;
break;
case 'sub':
result = num1 - num2;
break;
case 'mul':
result = num1 * num2;
break;
case 'div':
result = num2 !== 0 ? num1 / num2 : 'Cannot divide by zero';
break;
default:
result = 'Invalid operation';
}
resultElement.value = result;
}
</script>
</body>
</html>
Unit 4:
Theory:
Q2) Explain cookies in detail also explain how cookies work in browser. 4M
Cookies are small pieces of data stored on a user's device by a web browser during their interaction with a
website.
1. Creation and Storage:
• Cookies are created by web servers and sent to browsers in the HTTP response headers.
• Browsers store cookies locally on the user's device, typically in text files.
2. Structure:
• Cookies consist of key-value pairs, where the key is the name of the cookie, and the value is the
associated data.
• Additional attributes include domain, path, expiration date, and flags (e.g., Secure, HttpOnly).
3. Types of Cookies:
• Session Cookies:
• Temporary cookies that are stored only for the duration of a user's session.
• Deleted when the browser is closed.
• Persistent Cookies:
• Have an expiration date set by the server.
• Remain on the user's device until the expiration date or until manually deleted.
4. Usage:
• Authentication: Cookies can store user credentials or session tokens to maintain login status.
• Personalization: Used to remember user preferences, settings, and personalized content.
• Tracking and Analytics: Employed to collect information about user behavior for analytics and
advertising purposes.
5. Request and Response Cycle:
• When a user visits a website, their browser sends an HTTP request to the server.
• The server responds with an HTTP response that may include Set-Cookie headers to set cookies on
the user's device.
6. Sending Cookies:
• For subsequent requests to the same domain, the browser automatically includes relevant cookies in
the HTTP headers.
• Cookies are sent with each request to the domain, allowing the server to recognize and retrieve
user-specific information.
7. Expiration and Deletion:
• Session cookies are deleted when the browser is closed.
• Persistent cookies remain until their specified expiration date or until manually deleted by the user.
8. Security Considerations:
• Cookies may have flags to enhance security:
• Secure: Ensures that cookies are transmitted only over secure HTTPS connections.
• HttpOnly: Prevents cookies from being accessed through client-side JavaScript, reducing the
risk of cross-site scripting (XSS) attacks.
9. Limitations:
• Browsers impose limits on the number of cookies per domain and overall cookie storage.
• Privacy concerns have led to increased user controls and browser settings for managing cookies.
Q3) Describe how to read(create) and write cookies value explain in detail. 4M
1. Reading Cookies in JavaScript:
• Using document.cookie:
• JavaScript provides a document.cookie property to access all cookies associated with the
current document.
• Example:
var allCookies = document.cookie;
console.log(allCookies);
// Usage
var username = getCookie("username");
console.log("Username:", username);
// Usage
setCookie("username", "JohnDoe", 365, "/");
setCookie("language", "English", null, "/");
Q4) Describe how to delete cookies. 4M
Deleting cookies involves setting their expiration date to a time in the past or using the expires attribute. Here's
how you can delete cookies in JavaScript:
Delete by Setting Expiration Date:
• Set the expiration date of the cookie to a time in the past.
function deleteCookie(cookieName, path) {
var date = new Date();
date.setTime(date.getTime() - 1);
var expires = "expires=" + date.toUTCString();
document.cookie = cookieName + "=; " + expires + "; path=" + path;
}
// Usage
deleteCookie("username", "/");
// Usage
deleteAllCookies();
Q9) Explain open() method of window object with syntax and example. 4M
The window.open() method is a JavaScript method that opens a new browser window or tab. It provides a
way to dynamically create or open a new browser context.
Syntax:
window.open(url, windowName, windowFeatures);
• url (Optional): The URL to be opened in the new window. If not specified, an empty window is opened.
• windowName (Optional): A name for the new window. If a window with the same name already
exists, it will be reused; otherwise, a new window is created.
• windowFeatures (Optional): A string that specifies additional features for the new window, such as
size, position, and whether toolbars and scrollbars are displayed.
// Open a new window with a specific URL
var newWindow = window.open("https://example.com", "_blank");
Q10) Explain how to find out location object with its example. 4M
The window.location object in JavaScript provides information about the current URL of the browser. It allows
you to access and manipulate various components of the URL, such as the protocol, host, pathname, query
parameters, and more.
Location Object properties:
Property Description
hash Sets or returns the anchor part (#) of a URL
host Sets or returns the hostname and port number of a URL
hostname Sets or returns the hostname of a URL
href Sets or returns the entire URL
origin Returns the protocol, hostname and port number of a URL
pathname Sets or returns the path name of a URL
port Sets or returns the port number of a URL
protocol Sets or returns the protocol of a URL
search Sets or returns the querystring part of a URL
Example:
// Accessing properties of window.location
console.log("Full URL: " + window.location.href);
console.log("Protocol: " + window.location.protocol);
console.log("Host: " + window.location.host);
console.log("Hostname: " + window.location.hostname);
console.log("Pathname: " + window.location.pathname);
console.log("Search/Query: " + window.location.search);
console.log("Hash: " + window.location.hash);
CHILD WINDOW:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Child Window</title>
</head>
<body>
<p id="childParagraph">Initial content in the child window.</p>
</body>
</html>
Programs:
Q1) WJSP to change content of windows. 4M
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Window Content</title>
<script>
function changeContent() {
// Access the document object of the current window
var currentWindowDocument = window.document;
Example:
// Sample string
var text = "I have an apple and a banana. The apple is red.";
<script>
// You can add JavaScript for additional interactivity if needed
// For example, changing the text content dynamically
var rolloverText = document.querySelector('.rollover-text');
rolloverText.addEventListener('mouseover', function() {
rolloverText.textContent = 'You rolled over the text!';
});
rolloverText.addEventListener('mouseout', function() {
rolloverText.textContent = 'Hover over this text to see the roll over
effect!';
});
</script>
</body>
</html>
</body>
</html>
<script>
// Function to find non-matching characters using regex
function findNonMatchingCharacters(inputString, regexPattern) {
// Use the match() method with the regex pattern
var matchingCharacters = inputString.match(regexPattern);
// Find non-matching characters by subtracting matching characters from the
input
var nonMatchingCharacters = inputString.split('').filter(function(char) {
return matchingCharacters.indexOf(char) === -1;
});
return nonMatchingCharacters;
}
// Example usage
var inputString = "Hello123";
var regexPattern = /[^a-zA-Z]/; // Match any non-alphabetic character
</body>
</html>
Unit 6:
Theory:
Q1) List ways of protecting a web page describe any one of them. 4M
Ways of protecting Web Page:
1. Hiding your source code
2. Disabling the right Mouse Button
3. Hiding JavaScript
4. Concealing E-mail address
<script>
// Function to detect right mouse button click
function BreakInDetected() {
alert("Security Violation: Right mouse button is disabled.");
return false; // Prevents the default context menu from appearing
}
</script>
</head>
<body oncontextmenu="return BreakInDetected();">
<h1>Your Web Page Content Goes Here</h1>
</body>
</html>
Programs:
Q1) WJSP to create a pulldown menu with 3 browser option. Once user select any of the options then
user will be redirected to that site. 6M
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Browser Redirect</title>
</head>
<body>
<script>
// Function to redirect user based on selected option
function redirectUser() {
// Get the selected option value
var selectedBrowser = document.getElementById("browserSelect").value;
</body>
</html>
Q2) WJSP to modify status bar using mouseover and mouseout with link. 4M
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Status Bar Modification</title>
</head>
<body>
<p>Hover over the <a href="#" id="statusLink">link</a> to see the status bar
modification.</p>
<script>
// Get the link element by its id
var statusLink = document.getElementById("statusLink");
</body>
</html>
Q3) Create a banner of 5 images with slide show effect. (CSS PART IS NOT IMPORTANT) 4M
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Slideshow Banner</title>
<style>
/* Style for the banner container */
#bannerContainer {
width: 100%;
overflow: hidden;
}
</body>
</html>
<button type="submit">Submit</button>
</form>
<script>
// Function to validate menu selection
function validateSelection() {
// Get the selected value from the menu
var selectedOption = document.getElementById("menu").value;
</body>
</html>