CSS Finals QB (WITH ANSWERS)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

CSS Finals QB

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.

Q4) List any 4 CSS (Client-Side Scripting) language. 2M


1. JavaScript
2. HTML (Hypertext Markup Language)
3. CSS (Cascading Style Sheets)
4. TypeScript
5. CoffeeScript
6. Dart

Q5) Explain the structure of JS program. 2M/4M


1. Comments:
• Comments in JavaScript are used to provide explanations or annotate the code for better
understanding.
• Single-line comments start with //, and multi-line comments are enclosed between ‘/*’ and ‘*/’.
// This is a single-line comment

/*
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 + "!";
}

var greeting = greet("John");

5. Control Structures:
• Control structures like if, else, for, while, etc., are used to control the flow of the program.
var score = 85;

if (score >= 90) {


console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}

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");

Q6) Explain Data Types in JS. 2M/4M


1. Number:
• Represents numeric values, including integers and floating-point numbers.
• Example: var age = 25;
2. String:
• Represents sequences of characters and is enclosed in single (') or double (") quotes.
• Example: var name = "John";
3. Boolean:
• Represents a logical value, either true or false.
• Example: var isStudent = true;
4. Null:
• Represents the intentional absence of any object value.
• Example: var myVar = null;
5. Undefined:
• Indicates that a variable has been declared but has not been assigned a value.
• Example: var myVar; // undefined
6. Object:
• A complex data type that can store key-value pairs, forming properties and methods.
• Example:
var person = {
firstName: "John",
lastName: "Doe",
age: 30,
sayHello: function() {
console.log("Hello!");
}
};

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).

Q8) Getter and Setter method with example. 4M


In JavaScript, getter and setter functions are used to access and modify the properties of an object. Getter
functions return the value of the specified property, while setter functions can set the value of the specified
property. Example:
// Create a person object with a private property for name
const person = {
_name: "John Doe",

// Getter for getting the person's name


get name() {
return this._name;
},

// Setter for setting the person's name


set name(newName) {
if (newName.length > 0) {
this._name = newName;
} else {
console.log("Name cannot be empty.");
}
}
};

// Using the getter and setter


console.log("Current Name: " + person.name);
person.name = "Alice"; // Setting a new name
console.log("Updated Name: " + person.name);
person.name = ""; // Attempting to set an empty name

Q9) What are Literals in JS. 2M


They are fixed values that are used to express data directly, without the need for computation or evaluation.
Examples include numeric literals like ‘42’, string literals like "hello", Boolean literals like ‘true’ or ‘false’, and
object literals like ‘{ key: "value" }’.
Literals provide a straightforward way to define and work with constants in your code.

Q10) Define operators: (Any 1 for 2M) 2M


a. Comparison
b. Logical
c. Bitwise
d. Conditional (Ternary)

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"

Q11) Explain following methods in JS with examples: 4M


a. prompt()
b. alert()
c. confirm()
d. console()
a. prompt() Method:
• ++ The prompt() method is used to display a dialog box that prompts the user for input.
• It takes two arguments: the message to display in the dialog box and an optional default value for the
input field.
• The user can enter text into the input field and click "OK" to submit or "Cancel" to dismiss.
Example:
let userName = prompt("Please enter your name:", "John Doe");
if (userName !== null) {
alert("Hello, " + userName + "!");
}

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");

Q12) For loop VS For in Loop 4M


Aspect for Loop for...in Loop
Usage Iterates over the elements of an array or Iterates over the enumerable properties
executes a block of code a specified of an object (keys).
number of times.
Control More control over the loop variable and Less control over the order of iteration,
loop flow. Can iterate over arrays and especially for arrays (may not follow the
other iterable objects. order).
Suitability Suitable for iterating over numerical ranges Suitable for iterating over object
and arrays. properties.
Syntax for (initialization; condition; increment) { for (variable in object) {
// code to be executed // code to be executed
} }
Example for (let i = 0; i < 5; i++) { const person = {
console.log(i); name: 'John', age: 30, gender:
} 'male'};
for (let prop in person) {
console.log(prop, person[prop]);
}

Programs: (All programs 4M)


Q1) Palindrome
<script>
function isPalindrome(str) {
const reversedStr = str.split('').reverse().join('');
return str === reversedStr;
}

const inputStr = "racecar"; // Replace with your input


if (isPalindrome(inputStr)) {
console.log(`${inputStr} is a palindrome.`);
} else {
console.log(`${inputStr} is not a palindrome.`);
}
</script>

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);
}

return sum === number;


}

const inputNumber = 153; // Replace with your input


if (isArmstrong(inputNumber)) {
console.log(`${inputNumber} is an Armstrong number.`);
} else {
console.log(`${inputNumber} is not an Armstrong number.`);
}

Q3) Factorial of a Numbers


function factorial(n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorial(n - 1);
}

const inputNum = 5; // Replace with your input


console.log(`Factorial of ${inputNum} is: ${factorial(inputNum)}`);

Q4) Fibonacci series


function fibonacci(n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}

const numTerms = 8; // Replace with the number of terms you want


console.log(`Fibonacci series for ${numTerms} terms: `);
for (let i = 0; i < numTerms; i++) {
console.log(fibonacci(i));
}

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);

console.log(`Average Marks: ${average}`);


console.log(`Grade: ${grade}`);

Q6) Prime and Non-Prime Number.


function isPrime(num) {
if (num <= 1) {
return false;
}
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}

const testNumber = 17; // Replace with your input


if (isPrime(testNumber)) {
console.log(`${testNumber} is a prime number.`);
} else {
console.log(`${testNumber} is not a prime number.`);
}
Unit 2:
Theory:
Q1) Define array with examples. 2M
An array in JavaScript is a data structure that allows you to store multiple values in a single variable. Each
value in an array is called an element, and each element has a unique index starting from 0.

Example:
// Defining an array of numbers
const numericArray = [1, 2, 3, 4, 5];

// Defining an array of strings


const stringArray = ["apple", "banana", "orange", "grape"];

// Defining an array with mixed data types


const mixedArray = [1, "hello", true, [1, 2, 3], { key: "value" }];

// Defining an empty array


const emptyArray = [];

Q2) Explain ways for combining array elements into string. 4M


In JavaScript, there are several ways to combine array elements into a string. Some common ways:

Using join() method:


The join() method joins all elements of an array into a single string. You can specify a separator that will be
used between each element in the resulting string.
Example:
const array = ["apple", "banana", "orange"];
const resultString = array.join(", "); // Using ", " as the separator
console.log(resultString);
// Output: "apple, banana, orange"

Using toString() method:


The toString() method converts an array to a string by concatenating all the elements with commas. Note that
this method does not allow you to specify a custom separator.
Example:
const array = ["apple", "banana", "orange"];
const resultString = array.toString();
console.log(resultString);
// Output: "apple,banana,orange"

Using reduce() method:


The reduce() method can be used to concatenate array elements into a single string. This method provides more
flexibility, allowing you to use a custom concatenation logic.
Example:
const array = ["apple", "banana", "orange"];
const resultString = array.reduce((accumulator, currentValue) => accumulator + ", " +
currentValue);
console.log(resultString);
// Output: "apple, banana, orange"

Using concat() method with an empty string:


The concat() method is typically used for combining arrays, but it can also be used with an empty string to
concatenate array elements into a single string.
Example:
const array = ["apple", "banana", "orange"];
const resultString = "".concat(...array);
console.log(resultString);
// Output: "applebananaorange"

Q3) concat() VS join(). 4M


Feature concat() Method join() Method
Purpose Combines arrays or values into a new array Joins array elements into a string
or string. with a separator.
Return Value Returns a new array that is a concatenation Returns a string that is a
of input arrays or values. concatenation of array elements.
Modification of Does not modify the original array. Does not modify the original array.
Original Array
Custom Separator No direct provision for a custom separator. Allows you to specify a custom
separator.
Usage Example javascript const newArray = javascript const resultString =
array1.concat(array2); array.join(", ");
Concatenation of Can concatenate strings using arguments. Typically used for joining array
Strings elements into a string.
Flexibility Provides flexibility to concatenate multiple Primarily designed for joining array
arrays or values. elements with a separator.

Q4) Define methods: 2M/4M


a. slice()
b. pop()
c. push()
d. indexOf()
e. reverse()
f. unshift()
g. charAt()
h. shift()
slice():

Purpose: Extracts a portion of an array and returns it as a new array.


Usage Example: const newArray = originalArray.slice(startIndex, endIndex);

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();

Q5) Define types of functions. 2M


In JavaScript, there are several types of functions. Some common types:
Function Declaration:
Syntax:
function functionName(parameters) {
// function body
}
Example:
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Alice");

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;
}

Q6) Define function with its component. 4M


A function in JavaScript is a reusable block of code that performs a specific task or set of tasks. Functions help
in organizing code, promoting reusability, and making the code more modular. Functions can take input
parameters, perform actions based on those parameters, and return a result.
Function Keyword:
The function keyword is used to declare a function in JavaScript.
function functionName(parameters) {
// function body
}

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);

All the components used together:


function calculatePower(base, exponent) {
// Function Body
const result = Math.pow(base, exponent);
// Return Statement
return result;
}

// Function Call
const powerResult = calculatePower(2, 3);
console.log(powerResult); // Output: 8

Q7) Explain String functions with examples.: 4M


a. charAt()
b. toUpperCase()
c. toLowerCase()
d. subString()
e. substr()
f. replace()
g. split()
h. valueOf()
i. slice()
charAt():
• Purpose: Returns the character at the specified index in a string.
• Example:
• const str = "Hello";
• const character = str.charAt(1); // Returns "e"

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"

Q8) How to divide a string? 2M/4M


In JavaScript, you can divide a string using the split() method. The split() method splits a string into an array
of substrings based on a specified separator.
Example:
const originalString = "apple,orange,banana";
const separatedArray = originalString.split(",");

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);

// Sort the array


numbers.sort();

// Display sorted array


console.log("Sorted Array:", numbers);
};
</script>
</head>
<body>
<!-- HTML content -->
</body>
</html>

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"];

// Display the array


console.log("Fruits Array:", fruits);
};
</script>
</head>
<body>
<!-- HTML content -->
</body>
</html>

Q3) WJSP to call function from HTML. 2M


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Call Function from HTML</title>
<script>
// JavaScript function to be called
function greet() {
alert("Hello from JavaScript!");
}
</script>
</head>
<body>
<!-- HTML content -->
<button onclick="greet()">Click me</button>
</body>
</html>

Q4) WJSP to retrieve character from given position. 4M


function getCharacterAtPosition(inputString, position) {
// Check if the position is within the valid range
if (position < 0 || position >= inputString.length) {
return "Position out of range";
}

// Retrieve the character at the specified position


const character = inputString.charAt(position);

return character;
}

// Example usage:
const inputString = "Hello, World!";
const position = 7;

const result = getCharacterAtPosition(inputString, position);


console.log(`Character at position ${position}: ${result}`);
Unit 3:
Theory:
Q1) Explain mouse events with example. 4M
Mouse events in web development refer to interactions that occur when a user interacts with a webpage using
a mouse. There are several mouse events that you can handle in JavaScript, including click, double-click,
mouseover, mouseout, mousemove, etc.
Some common mouse events:
• Click Event: The click event occurs when the user clicks the left mouse button.
o Example:
<!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>

• 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>

• Mouse Over and Mouse Out Events:


o The mouseover event occurs when the mouse pointer enters an element, and the mouseout event
occurs when the mouse pointer leaves the element.
<!DOCTYPE html>
<html>
<head>
<title>Mouse Over/Out Event Example</title>
</head>
<body>
<div id="myElement">Hover over me</div>

<script>
const myElement = document.getElementById('myElement');

myElement.addEventListener('mouseover', function() {
this.style.backgroundColor = 'lightblue';
});

myElement.addEventListener('mouseout', function() {
this.style.backgroundColor = '';
});
</script>
</body>
</html>

• Mouse Move Event:


o The mousemove event occurs when the mouse pointer moves over an element.
<!DOCTYPE html>
<html>
<head>
<title>Mouse Move Event Example</title>
</head>
<body>
<div id="myDiv">Move your mouse over me</div>

<script>
document.getElementById('myDiv').addEventListener('mousemove', function(event) {
console.log(`Mouse coordinates: (${event.clientX}, ${event.clientY})`);
});
</script>
</body>
</html>

Q2) Explain Keyboard events with example. 4M


Keyboard events in web development refer to interactions that occur when a user interacts with a webpage
using a keyboard. There are several keyboard events that you can handle in JavaScript, including keydown,
keyup, and keypress. Some common Keyboard Events:
Keydown Event:
• The keydown event occurs when a key on the keyboard is pressed down.
<!DOCTYPE html>
<html>
<head>
<title>Keydown Event Example</title>
</head>
<body>
<input type="text" id="myInput" placeholder="Press a key">

<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>

Q3) Explain intrinsic JS functions with example. 4M


Intrinsic JavaScript functions, also known as built-in functions or native functions, are functions that are included
as part of the JavaScript language itself. These functions are available for use without the need for explicit
declaration or definition. They provide core functionality and are always available for use in any JavaScript
environment.
parseInt() and parseFloat():
• The parseInt() function parses a string and returns an integer. The parseFloat() function parses a string
and returns a floating-point number.
let intValue = parseInt("123");
let floatValue = parseFloat("123.45");

console.log(intValue); // Output: 123


console.log(floatValue); // Output: 123.45

isNaN():
• The isNaN() function checks whether a value is NaN (Not a Number) or not.
let result = isNaN("Hello");

console.log(result); // Output: true

Q4) Explain attributes for following form elements. 4M


a. Text area
b. Text field
c. Check box
d. Radio button
e. Submit button
f. Select
Text Area:
• rows: Specifies the visible number of rows in a text area.
• cols: Specifies the visible number of columns in a text area.
• Example:
<textarea rows="4" cols="50"></textarea>

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>

<form action="/submit" method="post">


<label for="uid">User ID:</label>
<input type="text" id="uid" name="uid" placeholder="Enter your User ID" required>

<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="Enter your
Password" required>

<input type="submit" value="Submit">


</form>

</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>

<h2>Select Fruits or Vegetables</h2>

<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>

<label for="foodList">Select a food:</label>


<select id="foodList" name="foodList">
<!-- Options will be dynamically added here -->
</select>
</form>

<script>
function updateOptions() {
var foodList = document.getElementById('foodList');
var category = document.querySelector('input[name="category"]:checked').value;

// Clear existing options


foodList.innerHTML = '';

// Add new options based on the selected category


if (category === 'fruits') {
addOption(foodList, 'apple', 'Apple');
addOption(foodList, 'banana', 'Banana');
addOption(foodList, 'orange', 'Orange');
} else if (category === 'vegetables') {
addOption(foodList, 'carrot', 'Carrot');
addOption(foodList, 'broccoli', 'Broccoli');
addOption(foodList, 'tomato', 'Tomato');
}
}
function addOption(selectElement, value, text) {
var option = document.createElement('option');
option.value = value;
option.text = text;
selectElement.add(option);
}
</script>

</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>

<h2>User Registration Form</h2>

<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>

<input type="submit" value="Submit" onclick="validateForm()">


</form>

<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;

// Name validation (at least 3 characters)


if (name.length < 3) {
document.getElementById('nameError').innerText = 'Name must be at least 3
characters';
return false;
}

// Email validation
var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
document.getElementById('emailError').innerText = 'Invalid email address';
return false;
}

// Password validation (at least 6 characters)


if (password.length < 6) {
document.getElementById('passwordError').innerText = 'Password must be at
least 6 characters';
return false;
}

// If all validations pass, you can proceed with form submission


alert('Form submitted successfully!');
// Add additional code for form submission or redirection here
}
</script>

</body>
</html>

Q4) Describe how to evaluate checkbox selection explain with example. 6M


Evaluating Checkbox Selection:
• To create a checkbox, use the <input> element with the type="checkbox" attribute-value pair.
• Checkboxes in a form have two states: checked or unchecked. Each checkbox operates independently
of others but can be grouped under a common name.
• JavaScript functions can be written to assess whether a checkbox is selected and then respond
accordingly based on the specific requirements of your application.
• Example:
<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>

Q5) Describe how to evaluate radio button explain with example. 6M


Evaluating radio buttons, it means determining or checking which option among a group of radio buttons has
been selected or picked by a user. Radio buttons allow users to choose only one option from a list of options.
The evaluation process involves inspecting the user's choice to understand their selection from the available
options within that particular group. This evaluation helps in processing the user's input or taking actions based
on their chosen option.
<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>

<label for="num1">Number 1:</label>


<input type="text" id="num1" placeholder="Enter number 1">

<label for="num2">Number 2:</label>


<input type="text" id="num2" placeholder="Enter number 2">

<br>

<button onclick="performOperation('add')">Addition (+)</button>


<button onclick="performOperation('sub')">Subtraction (-)</button>
<button onclick="performOperation('mul')">Multiplication (*)</button>
<button onclick="performOperation('div')">Division (/)</button>

<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);

var resultElement = document.getElementById('result');


var result;

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:

Q1) Define cookies. 2M


• Cookies are small pieces of data stored on a user's device by a web browser while the user is browsing
a website.
• They are designed to be a reliable mechanism for websites to remember information or to record the
user's browsing activity.

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);

Creating a Function for Specific Cookie:


• It's common to create a function to extract a specific cookie value for better code organization.
• Example:
function getCookie(cookieName) {
var name = cookieName + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var cookieArray = decodedCookie.split(';');
for (var i = 0; i < cookieArray.length; i++) {
var cookie = cookieArray[i].trim();
if (cookie.indexOf(name) == 0) {
return cookie.substring(name.length, cookie.length);
}
}
return "";
}

// Usage
var username = getCookie("username");
console.log("Username:", username);

2. Writing Cookies in JavaScript:


• Using document.cookie:
• The document.cookie property is also used to set or update cookies.
• Example:
// Set a cookie with a name, value, and optional attributes
document.cookie = "username=JohnDoe; expires=Thu, 31 Dec 2023 23:59:59 GMT; path=/";

// Set a session cookie (no expiration date)


document.cookie = "language=English; path=/";

Creating a Function for Setting Cookies:


• Creating a function can simplify the process of setting cookies with various attributes.
• Example:
function setCookie(cookieName, cookieValue, expirationDays, path) {
var date = new Date();
date.setTime(date.getTime() + (expirationDays * 24 * 60 * 60 * 1000));
var expires = "expires=" + date.toUTCString();
document.cookie = cookieName + "=" + cookieValue + "; " + expires + "; path=" + path;
}

// 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", "/");

Delete All Cookies:


• To delete all cookies, you can iterate through all existing cookies and set their expiration date to the
past.
function deleteAllCookies() {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
var cookieName = cookie.split('=')[0];
deleteCookie(cookieName, "/");
}
}

// Usage
deleteAllCookies();

Q5) Define browser with its structure in detail. 4M


1. User Interface (UI):
• The UI is what users interact with and includes elements like the address bar, back/forward
buttons, bookmarks, and various menus.
• UI components provide a way for users to control and customize their browsing experience.
2. Browser Engine:
• The browser engine is responsible for parsing HTML and CSS, rendering content on the screen,
and managing the Document Object Model (DOM) — a representation of the webpage's
structure.
• Popular browser engines include Blink (used by Google Chrome), Gecko (used by Mozilla
Firefox), and WebKit (used by Safari).
3. Rendering Engine:
• The rendering engine processes the HTML and CSS code of a webpage and displays it on the
user's screen.
• It handles tasks like layout, painting, and reflow to ensure that web content is visually presented
as intended.
4. JavaScript Engine:
• The JavaScript engine executes and interprets JavaScript code on web pages.
• Examples of JavaScript engines include V8 (used by Chrome), SpiderMonkey (used by Firefox),
and JavaScriptCore (used by Safari).
5. Networking Stack:
• The networking stack handles communication between the browser and web servers. It includes
protocols like HTTP and HTTPS for fetching web resources.
• Networking components manage requests, responses, and data transfer between the user's
device and remote servers.
6. Browser Storage:
• Browsers provide storage mechanisms for various purposes, including cookies, local storage, and
session storage.
• These storage options enable websites to store and retrieve data on the user's device.
7. Cache:
• Browsers use caching to store previously fetched resources locally, reducing the need to
download them again when revisiting a webpage.
• Caching improves page load times and reduces bandwidth usage.
8. Security Components:
• Browsers implement security features to protect users from malicious activities, such as phishing
and malware.
• Features include SSL/TLS for encrypted connections, secure storage of passwords, and
protection against cross-site scripting (XSS) and cross-site request forgery (CSRF) attacks.
9. Extensions and Add-ons:
• Browsers often support extensions or add-ons that enhance functionality, customize the user
interface, or provide additional features.
• Examples include ad blockers, password managers, and developer tools.
10. Browser Tabs and Windows:
• Browsers allow users to open multiple tabs and windows to navigate between different web
pages simultaneously.
• Tab management features include opening, closing, and grouping tabs.
11. Browser History:
• The browser maintains a history of visited web pages, allowing users to review and revisit
previously accessed content.

Q6) Applications of DOM. 2M


• The Document Object Model (DOM) is a programming interface for web documents.
• It represents the structure of a document as a tree of objects, where each object corresponds to a part of
the document, such as elements, attributes, and text.
• The DOM provides a way for programs to manipulate the structure, style, and content of web documents
dynamically.
Applications of DOM:
1. Dynamic Content Update:
• The DOM allows web developers to dynamically update the content of a webpage without
requiring a full page reload. This is commonly used in modern web applications to provide a
smoother and more responsive user experience.
2. Interactive User Interfaces:
• Web applications use the DOM to create interactive user interfaces. JavaScript can be used to
respond to user actions (clicks, inputs, etc.) and update the DOM accordingly, creating dynamic
and engaging interfaces.
3. Form Validation:
• When users submit forms on a webpage, JavaScript can use the DOM to validate input fields
before sending data to the server. This helps improve user experience by providing instant
feedback on the validity of the entered information.
4. AJAX (Asynchronous JavaScript and XML) Requests:
• AJAX enables the retrieval of data from a server without requiring a full page refresh. The
DOM is used to update specific parts of the webpage with the retrieved data, creating a more
seamless and interactive browsing experience.
5. Animation:
• Web developers use the DOM to create animations by manipulating the style and position of
HTML elements over time. This can be achieved using CSS transitions or JavaScript libraries for
more complex animations.
6. DOM Events:
• The DOM provides a mechanism for handling various events such as clicks, keypresses, and
mouse movements. JavaScript can listen for these events and respond by modifying the DOM,
enabling the creation of interactive and event-driven web applications.
7. Document Structure Manipulation:
• JavaScript can add, remove, or modify elements within the document structure using the DOM.
This allows for the dynamic creation of new elements or the restructuring of existing ones based
on user actions or application logic.
8. Cross-Browser Compatibility:
• The DOM provides a standardized interface for interacting with web documents, which helps
ensure cross-browser compatibility. Web developers can write code that works consistently
across different browsers.
9. Content Filtering and Sorting:
• The DOM enables the filtering and sorting of content on a webpage based on user preferences.
This is commonly seen in applications with lists or tables where users can customize the display
of information.
10. Single Page Applications (SPAs):
• SPAs, which load a single HTML page and dynamically update content as the user interacts with
the application, heavily rely on the DOM for rendering and managing different views.

Q7) List Browser names (ANY 4). 2M


• Google Chrome
• Mozilla Firefox
• Microsoft Edge
• Apple Safari
• Opera
• Brave
• Vivaldi
• Internet Explorer
• Tor Browser
• UC Browser
• Epic Privacy Browser

Q8) Explain windows method in detail (any 6). 4M/6M


Method Description
addEventListener() Attaches an event handler to the window
alert() Displays an alert box with a message and an OK button
atob() Decodes a base-64 encoded string
blur() Removes focus from the current window
btoa() Encodes a string in base-64
clearInterval() Clears a timer set with setInterval()
clearTimeout() Clears a timer set with setTimeout()
close() Closes the current window
confirm() Displays a dialog box with a message and an OK and a Cancel button
focus() Sets focus to the current window
getComputedStyle() Gets the current computed CSS styles applied to an element
getSelection() Returns a Selection object representing the range of text selected by the user
matchMedia() Returns a MediaQueryList object representing the specified CSS media query
string
moveBy() Moves a window relative to its current position
moveTo() Moves a window to the specified position
open() Opens a new browser window
print() Prints the content of the current window
prompt() Displays a dialog box that prompts the visitor for input
removeEventListener() Removes an event handler from the window
requestAnimationFrame() Requests the browser to call a function to update an animation before the next
repaint
resizeBy() Resizes the window by the specified pixels
resizeTo() Resizes the window to the specified width and height
scroll() Deprecated. This method has been replaced by the scrollTo() method.
scrollBy() Scrolls the document by the specified number of pixels
scrollTo() Scrolls the document to the specified coordinates
setInterval() Calls a function or evaluates an expression at specified intervals (in milliseconds)
setTimeout() Calls a function or evaluates an expression after a specified number of
milliseconds
stop() Stops the window from loading

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");

// Open a new window with custom features


var customFeatures = "width=600,height=400,top=100,left=100,toolbar=no,scrollbars=yes";
var customWindow = window.open("https://example.com", "CustomWindow", customFeatures);

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

Location Object Methods


Method Description
assign() Loads a new document
reload() Reloads the current document
replace() Replaces the current document with a new one

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);

// Modifying the URL


window.location.href = "https://new-url.com";

Q11) Persistent cookies VS Session cookies. 2M


Feature Persistent Cookies Session Cookies
Duration Remain on the user's device for a Exist only for the duration of the user's session
specified duration, even after the browser and are deleted when the browser is closed.
is closed and reopened.
Expiration Have an expiration date set, and they Expire automatically when the browser session
persist until that date or until manually ends.
deleted by the user.
Purpose Used for long-term data storage, such as Ideal for temporary storage of information
user preferences, login information, or needed only during the user's current session,
tracking user behavior over time. like session tokens or shopping cart items.
Storage Limit Can store larger amounts of data Typically have smaller storage capacity.
compared to session cookies.
Security Considered less secure because they Generally more secure as they are short-lived
Implications persist for a longer period, making them and don't persist after the browser is closed.
a potential target for security threats.
Example Use Remembering user preferences on a Storing a user's authentication token during a
Case website. single browsing session.

Q12) Accessing elements of another child window. 4M


Accessing elements of another child window in web development involves using the window object and its
properties. When a new window or tab is opened using window.open(), you can interact with elements in that
window by referencing its window object.
Example: (PARENT WINDOW)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Parent Window</title>
<script>
function openChildWindow() {
// Open a new window and store its reference in a variable
var childWindow = window.open("child.html", "ChildWindow",
"width=400,height=300");

// Access elements in the child window


if (childWindow) {
// Example: Change the content of a paragraph in the child window
childWindow.document.getElementById("childParagraph").innerHTML = "Content
updated from the parent window.";
}
}
</script>
</head>
<body>
<button onclick="openChildWindow()">Open Child Window</button>
</body>
</html>

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;

// Access an element by its ID and change its content


var contentElement = currentWindowDocument.getElementById("content");
if (contentElement) {
contentElement.innerHTML = "New Content!";
}
}
</script>
</head>
<body>
<h1 id="content">Original Content</h1>
<button onclick="changeContent()">Change Content</button>
</body>
</html>
Unit 5:
Theory:
Q1) Describe Regular expression. Explain search method used in regex with suitable examples. 4M
A regular expression, often abbreviated as regex, is a powerful tool for pattern matching and manipulation
of strings. It is a sequence of characters that forms a search pattern. Regular expressions are widely used in
programming, text processing, and data validation tasks.

‘search’ Method in Regex:


The search method in JavaScript is used to search for a specified pattern in a string. It returns the index of the
first occurrence of the pattern, or -1 if the pattern is not found. The search method is often used with regular
expressions.

Example:
// Sample string
var text = "I have an apple and a banana. The apple is red.";

// Regular expression to search for the word "apple"


var pattern = /apple/;

// Using the search method


var result = text.search(pattern);

// Displaying the result


if (result !== -1) {
console.log("Pattern found at index:", result);
} else {
console.log("Pattern not found.");
}

Regular Expression Modifiers:


Regular expressions can include modifiers that affect the search. For example, the "i" modifier makes the search
case-insensitive. Let's modify the example to make the search case-insensitive:
Example:
// Sample string
var text = "I have an Apple and a banana. The APPLE is red.";

// Regular expression with the "i" modifier for case-insensitivity


var pattern = /apple/i;

// Using the search method


var result = text.search(pattern);

// Displaying the result


if (result !== -1) {
console.log("Pattern found at index:", result);
} else {
console.log("Pattern not found.");
}
Q2) Explain text roll over with suitable example. 4M
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Roll Over Example</title>
<style>
/* Styling for the default state */
.rollover-text {
color: blue;
transition: color 0.3s ease; /* Smooth color transition over 0.3 seconds */
}

/* Styling for the hover state */


.rollover-text:hover {
color: red;
}
</style>
</head>
<body>
<p class="rollover-text">Hover over this text to see the roll over effect!</p>

<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>

Q3) Validate UID with regex. 4M


// Regular expression for UID validation
var uidPattern = /^[a-zA-Z0-9_-]{3,16}$/;

// Example UID to validate


var exampleUID = "user123";

// Test the UID against the regex pattern


if (uidPattern.test(exampleUID)) {
console.log("UID is valid.");
} else {
console.log("UID is not valid.");
}
Programs:
Q1) WJSP for creating a frame structure. Fruits Vegetables are links. When user click on anyone of the
link the data will appear on the frame2. 6M
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frame Structure Example</title>
</head>
<body>

<!-- Frame 1 with links -->


<frame src="fruits.html" name="frame1" scrolling="no">

<!-- Frame 2 for displaying data -->


<frame src="" name="frame2">

<!-- JavaScript to update Frame 2 content -->


<script>
// Function to update Frame 2 content based on the clicked link
function updateFrame(link) {
// Get the href attribute of the clicked link
var linkSrc = link.getAttribute("href");

// Update Frame 2 with the new source


parent.frame2.location.href = linkSrc;

// Prevent the default behavior of the link


return false;
}
</script>

</body>
</html>

Q2) WJSP to find non-matching characters in regex. 4M


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Non-Matching Characters Example</title>
</head>
<body>

<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

var result = findNonMatchingCharacters(inputString, regexPattern);


console.log("Non-matching characters:", result);
</script>

</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

Hiding your source code:


• Cache Storage: Webpage source code, including JavaScript, is stored in the browser cache, a part of
computer memory.
• Potential Access: Tech-savvy visitors can access the cache and view the webpage's source code.
• Protection Measures:
1. Disable Right Mouse Button: Prevents visitors from using the "View Source" option in the context
menu, hiding HTML and JavaScript.
2. Limitations of Right Mouse Button Disablement: Doesn't fully secure the code; visitors can still
use the "View" menu's "Source" option.
• Enhanced Security:
• Server-Side JavaScript Storage: Store JavaScript on the web server instead of embedding it
directly into the webpage.
• Dynamic Retrieval: Browser fetches JavaScript from the server when needed by the webpage.
• Invisibility to Visitors: This method ensures that JavaScript remains invisible, even if visitors attempt to
inspect the source code.
• Limitations of Protection Measures: While providing some level of protection, it's crucial to recognize
that no method can make code entirely inaccessible; determined individuals with technical knowledge
can still find ways to access it.

Disable Right Mouse Button:


• Location: JavaScript code placed in the <head> tag of the webpage.
• Objective: Prevents visitors from using the right mouse button.
• Action: Utilizes the BreakInDetected() function to display a security violation message in a dialog box
when the right mouse button is clicked.
• JavaScript Function: BreakInDetected():
• Trigger: Called whenever the visitor clicks the right mouse button.
• Action: Displays a security violation message in a dialog box.
• Conditions: Activated if any button other than the left mouse button is clicked.
• Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Disable Right Mouse Button</title>

<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>

Q2) List frameworks of JS explain its application. (Write any 4 to 6 of these) 4M


1. React:
• Application: Developed by Facebook, React is used for building user interfaces, especially for
single-page applications (SPAs). It allows for the creation of reusable UI components, making UI
development efficient and manageable.
2. Angular:
• Application: Angular, maintained by Google, is a comprehensive framework for building
dynamic web applications. It provides features like two-way data binding, dependency
injection, and a modular structure, making it suitable for large-scale projects.
3. Vue.js:
• Application: Vue.js is a progressive JavaScript framework used for building user interfaces. It
is known for its simplicity and flexibility, making it easy to integrate into projects and suitable
for both small-scale and large-scale applications.
4. Node.js:
• Application: Node.js is a server-side JavaScript runtime that allows the execution of JavaScript
code outside the browser. It is commonly used for building scalable and high-performance
network applications.
5. Express.js:
• Application: Built on top of Node.js, Express.js is a minimal and flexible web application
framework. It simplifies the development of server-side logic, making it easier to build APIs and
web applications.
6. jQuery:
• Application: jQuery is a fast and lightweight JavaScript library. It simplifies HTML document
traversal, event handling, and animation. While its usage has decreased with the rise of modern
frameworks, it is still used for quick prototyping and in existing projects.
7. Redux:
• Application: Redux is a predictable state container for JavaScript applications. It is often used
with React to manage the state of an application in a predictable way, facilitating debugging
and testing.
8. D3.js:
• Application: D3.js is a powerful library for creating data visualizations using HTML, SVG, and
CSS. It is commonly used for building interactive and dynamic charts, graphs, and maps.
9. Next.js:
• Application: Next.js is a React-based framework that simplifies the development of React
applications. It provides features like server-side rendering and helps in generating static
websites.
10. Electron:
• Application: Electron is an open-source framework for building cross-platform desktop
applications using web technologies. It allows developers to create native desktop applications
for Windows, macOS, and Linux.

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>

<label for="browserSelect">Choose a Browser:</label>


<select id="browserSelect" onchange="redirectUser()">
<option value="" disabled selected>Select a Browser</option>
<option value="chrome">Google Chrome</option>
<option value="firefox">Mozilla Firefox</option>
<option value="edge">Microsoft Edge</option>
</select>

<script>
// Function to redirect user based on selected option
function redirectUser() {
// Get the selected option value
var selectedBrowser = document.getElementById("browserSelect").value;

// Redirect based on the selected option


switch (selectedBrowser) {
case "chrome":
window.location.href = "https://www.google.com/chrome/";
break;
case "firefox":
window.location.href = "https://www.mozilla.org/en-US/firefox/";
break;
case "edge":
window.location.href = "https://www.microsoft.com/en-us/edge";
break;
default:
// Do nothing if no option is selected
break;
}
}
</script>

</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");

// Add mouseover event listener


statusLink.addEventListener("mouseover", function() {
// Change the status bar text when mouse is over the link
window.status = "You are hovering over the link!";
});

// Add mouseout event listener


statusLink.addEventListener("mouseout", function() {
// Restore the status bar text when mouse moves out
window.status = "";
});
</script>

</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;
}

/* Style for the images in the banner */


.bannerImage {
width: 100%;
display: none;
}
</style>
</head>
<body>

<!-- Banner container -->


<div id="bannerContainer">
<!-- Images in the slideshow -->
<img class="bannerImage" src="image1.jpg" alt="Image 1">
<img class="bannerImage" src="image2.jpg" alt="Image 2">
<img class="bannerImage" src="image3.jpg" alt="Image 3">
<img class="bannerImage" src="image4.jpg" alt="Image 4">
<img class="bannerImage" src="image5.jpg" alt="Image 5">
</div>
<script>
// JavaScript for the image slideshow
var currentIndex = 0;
var images = document.querySelectorAll('.bannerImage');

// Function to show the next image in the slideshow


function showNextImage() {
images[currentIndex].style.display = 'none'; // Hide the current image
currentIndex = (currentIndex + 1) % images.length; // Move to the next image
images[currentIndex].style.display = 'block'; // Show the next image
}

// Set an interval to automatically advance the slideshow (every 3 seconds in this


example)
setInterval(showNextImage, 3000);
</script>

</body>
</html>

Q4) WJSP to validate menu selection. (CSS PART IS NOT IMPORTANT) 6M


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Menu Selection Validation</title>
<style>
/* Style for error message */
#errorMessage {
color: red;
}
</style>
</head>
<body>

<h2>Menu Selection Validation</h2>

<form id="menuForm" onsubmit="return validateSelection()">


<label for="menu">Select an option:</label>
<select id="menu" name="menu">
<option value="" disabled selected>Select an option</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>

<!-- Display error message -->


<p id="errorMessage"></p>

<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;

// Check if a valid option is selected


if (selectedOption === "") {
// Display error message
document.getElementById("errorMessage").innerText = "Please select an
option.";

// Prevent form submission


return false;
} else {
// Clear error message
document.getElementById("errorMessage").innerText = "";

// Allow form submission


return true;
}
}
</script>

</body>
</html>

You might also like