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

JavaScript Complete Exam Material

This document serves as comprehensive exam material for Client-Side Scripting using JavaScript, covering various units including basics, strings, arrays, forms, and events. It includes exam preparation questions, theory answers, and practical JavaScript code examples for functions, arrays, and event handling. Additionally, it discusses concepts like variable scope, form objects, and array methods, providing a solid foundation for understanding JavaScript programming.

Uploaded by

anupsambhex545
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

JavaScript Complete Exam Material

This document serves as comprehensive exam material for Client-Side Scripting using JavaScript, covering various units including basics, strings, arrays, forms, and events. It includes exam preparation questions, theory answers, and practical JavaScript code examples for functions, arrays, and event handling. Additionally, it discusses concepts like variable scope, form objects, and array methods, providing a solid foundation for understanding JavaScript programming.

Uploaded by

anupsambhex545
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Client-Side Scripting (JavaScript) –

Combined Exam Material


Unit 1: Basics of JavaScript

Unit 2: Strings and Arrays

Unit 3: Forms and Events

Unit 4: Cookies, Windows, and Timers

Unit 5: Frames, Regular Expressions, and Validation

Unit 6: Banners, Menus, Scrolling Text, Slideshow

Client-Side Scripting (JavaScript) - Exam


Preparation
Q a) List the features of JavaScript:

1. Lightweight and Interpreted

2. Object-Oriented

3. Client-Side Execution

4. Event-Driven

5. Platform Independent

6. Case Sensitive

7. Dynamic Typing
Q b) List six types of values in JavaScript:

1. Number 2. String 3. Boolean 4. Object 5. Undefined 6. Null

Q c) What is conditional operator in JavaScript?

Syntax: condition ? expression1 : expression2;

Example: let result = (age >= 18) ? "Adult" : "Minor";

Q a) JavaScript to display WELCOME message:

<script> alert("WELCOME"); </script>

Q b) Print sum of odd numbers between 1 to 10:

<script>

let sum = 0;

for (let i = 1; i <= 10; i++) {

if (i % 2 !== 0) sum += i;

document.write("Sum of odd numbers: " + sum);

</script>

Q c) Difference between prompt() and alert():

| Feature | prompt() | alert() |

|----------------|-------------------------------|------------------------|

| Purpose | Take input from user | Show message |

| Returns value | Yes | No |

| Input box | Yes | No |

| Syntax | prompt("Name:") | alert("Hello!") |


Q b) Use of getters and setters:

Used to access and modify object properties.

Example:

let person = {

get fullName() { return this.firstName + " " + this.lastName; },

set fullName(name) { [this.firstName, this.lastName] = name.split(" "); }

};

Q c) Four arithmetic and logical operators:

Arithmetic: +, -, *, /

Logical: &&, ||, !

Q b) JavaScript to display first 20 even numbers:

<script>

let count = 0, num = 2;

while (count < 20) {

document.write(num + "<br>");

num += 2;

count++;

</script>

Q c) Syntax and example of prompt():

Syntax: prompt("message", "default");

Example:
let name = prompt("Enter your name:", "Guest");

alert("Welcome " + name);

Q a) Property, Method and Dot Syntax:

Property: Variable inside object (car.color)

Method: Function inside object (car.start())

Dot Syntax: Used to access (car.start();)

Q b) Identify running browser:

<script> document.write("Browser: " + navigator.appName); </script>

Q c) Check if number is prime:

<script>

let num = parseInt(prompt("Enter number:"));

let isPrime = true;

if (num <= 1) isPrime = false;

for (let i = 2; i <= Math.sqrt(num); i++) {

if (num % i === 0) isPrime = false;

alert(isPrime ? "Prime" : "Not Prime");

</script>

Q b) Addition of two numbers:

<script>

let a = parseInt(prompt("Enter first:"));

let b = parseInt(prompt("Enter second:"));


alert("Sum = " + (a + b));

</script>

Q a) Use of break and continue:

break: exits loop. continue: skips current iteration.

Example break:

for (let i = 1; i <= 10; i++) {

if (i == 5) break;

document.write(i + "<br>");

Example continue:

for (let i = 1; i <= 5; i++) {

if (i == 3) continue;

document.write(i + "<br>");

Client-Side Scripting (JavaScript) –


Exam-Oriented Theory Answers
Q1a) Define function and its types with example.
Definition of Function:
In JavaScript, a function is a block of reusable code that performs a specific task. Functions
are used to group code into one unit so it can be called whenever needed. This promotes
code reusability, modularity, and readability.

Functions are declared using the function keyword and can accept parameters and return
values.

Syntax:
function functionName(parameter1, parameter2) {
// code to be executed
}
You can call a function using:
functionName(arg1, arg2);

Types of Functions in JavaScript:


1. Named Function (Regular function):
function greet() {
console.log("Hello, welcome!");
}
greet();

2. Anonymous Function:
var display = function() {
console.log("This is an anonymous function.");
};
display();

3. Arrow Function (ES6):


const add = (a, b) => a + b;

4. Immediately Invoked Function Expression (IIFE):


(function() {
console.log("This is an IIFE function.");
})();

Q1b) Differentiate between concat() and join() methods of array object.


| Feature | concat() Method | join() Method |
|------------------|--------------------------------------------|---------------------------------------------|
| Purpose | Combines two or more arrays | Joins all elements of an array into a
string |
| Return Type | Returns a new array | Returns a string |
| Original Array | Does not modify original array | Does not modify original array
|
| Syntax | array1.concat(array2) | array.join(separator) |
| Example | arr1.concat(arr2) | arr.join(", ") |

Q1c) Explain the use of push and pop functions


push():
The push() method is used to add one or more elements at the end of an array.
Example:
let fruits = ['Apple', 'Banana'];
fruits.push('Mango'); // ['Apple', 'Banana', 'Mango']

pop():
The pop() method removes the last element from an array.
Example:
let fruits = ['Apple', 'Banana', 'Mango'];
fruits.pop(); // ['Apple', 'Banana']

Q2a) Write a JavaScript function to insert a string within a string at a


particular position
function insertString(mainStr, insertStr, position) {
return mainStr.slice(0, position) + insertStr + mainStr.slice(position);
}
let result = insertString("Hello World", " Beautiful", 5);
console.log(result); // Output: "Hello Beautiful World"

Q2b) Create a function that takes a string as input, process it and returns
the reversed string.
function reverseString(str) {
return str.split('').reverse().join('');
}
let reversed = reverseString("hello");
console.log(reversed); // Output: "olleh"

Q3a) What is string.


A string in JavaScript is a sequence of characters enclosed in single quotes (''), double
quotes ("") or backticks (``). Strings are used to represent and manipulate text.
Example:
let name = "John";
let message = 'Welcome to JavaScript';

Q3b) Define array


An array in JavaScript is a special variable that can hold multiple values in a single variable
name.
Example:
let colors = ["Red", "Green", "Blue"];

Q3c) Write a four point difference between group of check-box and group
of radio buttons.
| Feature | Checkboxes | Radio Buttons |
|-----------------------|--------------------------------------------|---------------------------------------------|
| Selection | Allows multiple selections | Only one selection at a time |
| Input Type | <input type="checkbox"> | <input type="radio"> |
| Use Case | For choosing multiple options | For choosing one option from a
group |
| Grouping | Work independently | Grouped using same name attribute
|

Q4a) Give the syntax of "with" statement/clause of javascript with


suitable example.
Syntax:
with (object) {
// statements to be executed
}

Example:
let person = {
name: "John",
age: 30
};

with (person) {
console.log(name); // John
console.log(age); // 30
}

Q5a) Write a javascript to call a function with arguments for subtraction


of two numbers.
function subtract(a, b) {
return a - b;
}
let result = subtract(10, 4);
console.log("Subtraction:", result); // Output: 6

Q5b) Write a javascript function to count the number of Vowels in a given


string.
function countVowels(str) {
let vowels = ['a', 'e', 'i', 'o', 'u'];
let count = 0;
for (let i = 0; i < str.length; i++) {
if (vowels.includes(str[i].toLowerCase())) {
count++;
}
}
return count;
}
let result = countVowels("Education");
console.log("Vowel Count:", result); // Output: 5

Q5d) Write a short note on:


i) Combining Array Elements into a string.
ii) Changing Elements of the Array.
i) Combining Array Elements into a String:
Use join() method.
Example:
let colors = ["Red", "Green", "Blue"];
let result = colors.join(" - "); // "Red - Green - Blue"

ii) Changing Elements of the Array:


Access elements by index.
Example:
let fruits = ["Apple", "Banana", "Mango"];
fruits[1] = "Orange"; // Changes "Banana" to "Orange"

Q6a) How will you define function?


A function in JavaScript is a reusable block of code used to perform a specific task.

Example:
function greet(name) {
console.log("Hello " + name);
}
greet("John"); // Output: Hello John

Q6d) Write a JavaScript that find and displays number of duplicate values
in an array.
function findDuplicates(arr) {
let counts = {};
let duplicates = [];

for (let i = 0; i < arr.length; i++) {


counts[arr[i]] = (counts[arr[i]] || 0) + 1;
}

for (let key in counts) {


if (counts[key] > 1) {
duplicates.push(key);
}
}

console.log("Duplicate values:", duplicates);


console.log("Number of duplicates:", duplicates.length);
}
findDuplicates([1, 2, 3, 2, 3, 4, 5, 1]);

Q7b) State and explain any two properties of array object.


1. length:
Represents the number of elements in the array.
Example:
let colors = ["Red", "Green", "Blue"];
console.log(colors.length); // 3

2. constructor:
Returns the function that created the array's prototype.
Example:
let arr = [1, 2, 3];
console.log(arr.constructor); // function Array()...
Q8a) Write a java script to convert string to number.
let str = "123";
let num1 = Number(str);
let num2 = parseInt(str);
let num3 = +str;

console.log(num1); // 123
console.log(num2); // 123
console.log(num3); // 123

Q8c) Differentiate between call by value and call by reference.


| Feature | Call by Value | Call by Reference |
|------------------|------------------------------------------|----------------------------------------|
| Definition | Passes copy of value | Passes reference/address |
| Data Type | Primitive types | Objects and arrays |
| Original Value | Not affected | Can be changed |
| Example | function(a) { a = 10; } | function(obj) { obj.key = value; } |

Client-Side Scripting (JavaScript) –


Additional Theory Questions
Q1a) State the use of text component.
Text components in JavaScript (usually <input type="text"> in HTML) are used to allow
users to enter plain text.
They are widely used in forms where users need to enter names, email addresses, or any
kind of alphanumeric data.

Example:
<input type="text" id="username" name="username">

Q1b) Define Event.


An event in JavaScript refers to an occurrence or action that takes place in the browser,
which can be detected and handled using JavaScript. Examples of events include clicking a
button (onclick), pressing a key (onkeypress), or submitting a form (onsubmit).
Q2a) Explain the scope of variable with example.
Scope of a variable defines the accessibility or visibility of a variable.

Types of Scope:
1. Global Scope – A variable declared outside any function.
2. Local Scope – A variable declared inside a function.
3. Block Scope – Introduced in ES6 using let and const.

Example:
var globalVar = "I am global"; // Global Scope
function test() {
var localVar = "I am local"; // Local Scope
if(true){
let blockVar = "I am block scoped"; // Block Scope
console.log(blockVar);
}
console.log(localVar);
}
console.log(globalVar);

Q2b) Explain form object and elements.


The form object in JavaScript represents an HTML <form> element and is used to manage
form elements like text fields, radio buttons, and submit buttons.

Accessing the form:


document.forms[0]; // Accesses first form

Accessing form elements:


document.forms[0].elements["username"].value;

Q2c) Write a JavaScript to illustrate keyboard event.


<input type="text" onkeydown="showKey(event)">
<script>
function showKey(e) {
alert("Key pressed: " + e.key);
}
</script>
Q3a) State the use of CharCodeAt() & fromCharCode() methods.
charCodeAt() – Returns the Unicode of the character at a specified index.
Example:
"ABC".charCodeAt(0); // returns 65

fromCharCode() – Converts Unicode values to characters.


Example:
String.fromCharCode(65); // returns "A"

Q3b) State the use of text component.


Text components are used to input data from the user in the form of strings, such as name,
email, and address fields in a form.
Example:
<input type="text" id="email" placeholder="Enter your email">

Q4a) Explain all term related to form object & elements.


1. Form Object – Represents the form itself.
2. Elements – Refers to input fields, checkboxes, radio buttons, etc.
3. Action – URL to send form data to.
4. Method – HTTP method used to submit form (GET/POST).
5. Submit – Submits the form.
6. Reset – Resets the form values.
7. Name – Unique identifier of the form.
8. Value – Holds current data entered in a form field.

Q4b) Write a javascript to create three categories Fruit, Flower and Color,
based on the selection of category the items in the option list must get
changed.
<select id="category" onchange="updateItems()">
<option value="Fruit">Fruit</option>
<option value="Flower">Flower</option>
<option value="Color">Color</option>
</select>
<select id="items"></select>
<script>
function updateItems() {
let category = document.getElementById("category").value;
let items = document.getElementById("items");
items.innerHTML = "";

let data = {
Fruit: ["Apple", "Banana", "Mango"],
Flower: ["Rose", "Lily", "Tulip"],
Color: ["Red", "Green", "Blue"]
};

data[category].forEach(item => {
let option = document.createElement("option");
option.text = item;
items.add(option);
});
}
</script>

Q5b) Give syntax of the use of "with" statement clause in JavaScript using
suitable example.
Syntax:
with (object) {
statement;
}

Example:
let person = {name: "John", age: 25};
with (person) {
console.log(name); // John
console.log(age); // 25
}

Q6b) Write HTML script that displays dropdown list containing options
Hyderabad, Pune, Nagpur. Write proper JavaScript such that when user
selects any options corresponding description of city and image of the city
appear in table below on the same page.
<select id="cities" onchange="showInfo()">
<option value="Hyderabad">Hyderabad</option>
<option value="Pune">Pune</option>
<option value="Nagpur">Nagpur</option>
</select>
<table border="1" id="cityTable">
<tr>
<td id="desc"></td>
<td><img id="cityImg" width="100"></td>
</tr>
</table>
<script>
function showInfo() {
let city = document.getElementById("cities").value;
let desc = document.getElementById("desc");
let img = document.getElementById("cityImg");

let info = {
Hyderabad: ["Hyderabad is known as the City of Pearls.", "hyderabad.jpg"],
Pune: ["Pune is a cultural capital of Maharashtra.", "pune.jpg"],
Nagpur: ["Nagpur is famous for oranges and central location.", "nagpur.jpg"]
};

desc.innerText = info[city][0];
img.src = info[city][1];
}
</script>

Q7b) State the uses of Forms.


Forms in HTML/JavaScript are used to collect user input data such as name, email, feedback,
etc. JavaScript can be used to validate, submit, and manipulate form data before sending it
to a server.

Common uses:
- User login and registration
- Feedback and contact forms
- Online surveys
- Data collection interfaces

Q7c) Write a java script to create user and password field and verify using
script.
<input type="text" id="user" placeholder="Username">
<input type="password" id="pass" placeholder="Password">
<button onclick="validate()">Login</button>
<script>
function validate() {
let u = document.getElementById("user").value;
let p = document.getElementById("pass").value;
if (u === "admin" && p === "1234") {
alert("Login successful");
} else {
alert("Invalid credentials");
}
}
</script>

Q8a) Write a JavaScript function to insert a string within a string at a


particular position
function insertString(str, insert, position) {
return str.slice(0, position) + insert + str.slice(position);
}
console.log(insertString("Hello World", " Beautiful", 5));

Q8b) Create a function that takes a string as input, process it and returns
the reversed string.
function reverseString(str) {
return str.split("").reverse().join("");
}
console.log(reverseString("JavaScript"));

Q9a) Explain onClick and onChange events with their purpose.


onClick:
Triggered when an element is clicked.
Example:
<button onclick="alert('Clicked')">Click Me</button>

onChange:
Triggered when the value of an element changes.
Example:
<select onchange="alert('Changed')">
<option>One</option>
<option>Two</option>
</select>
Q9b) Create a javascript where a keypress event updates a label
dynamically with the pressed key and change the background color.
<input type="text" onkeypress="updateLabel(event)">
<label id="keyLabel">Pressed Key: </label>
<script>
function updateLabel(event) {
document.getElementById("keyLabel").innerText = "Pressed Key: " + event.key;
document.body.style.backgroundColor = "#" +
Math.floor(Math.random()*16777215).toString(16);
}
</script>

Client-Side Scripting (JavaScript) –


Cookies, Windows, and Timing Events
Q1a) Enlist and explain the use of any two intrinsic JavaScript functions.
1. parseInt(): Converts a string to an integer.
Example: parseInt("123"); // Returns 123

2. isNaN(): Checks whether a value is NaN (Not a Number).


Example: isNaN("abc"); // Returns true

Q1b) Write JavaScript to open a new window.


<script>
function openNewWindow() {
window.open("https://www.example.com", "_blank", "width=500,height=400");
}
</script>
<button onclick="openNewWindow()">Open Window</button>

Q2a) How to create cookies in JavaScript? Explain with example.


Cookies in JavaScript are created using `document.cookie`.

Syntax:
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2025 12:00:00 UTC; path=/";

Example:
<script>
document.cookie = "user=Admin; expires=Sat, 31 Dec 2025 12:00:00 UTC; path=/";
</script>

Q2c) Write a function that prompt the user for a color and uses what they
select to set the background color of the new webpage opened.
<script>
function openColorPage() {
let color = prompt("Enter a color:");
let newWindow = window.open("", "_blank", "width=400,height=300");
newWindow.document.write(`<body style='background-color:${color};'><h1>New
Page</h1></body>`);
}
</script>

Q3a) Explain flow to create cookies in JavaScript.


Flow to create cookies in JavaScript:
1. Define the cookie name and value.
2. Optionally set expiry date, path, domain, and secure flag.
3. Assign the cookie string to document.cookie.

Example:
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2025 12:00:00 UTC; path=/";

Q3b) Write a function that prompts the user for select color and what
they select to set the background color of the new webpage opened.
<script>
function setColorPage() {
let color = prompt("Enter a color:");
let win = window.open("", "_blank", "width=400,height=400");
win.document.write("<body style='background-color:" + color + ";'><h2>Color
Set!</h2></body>");
}
</script>
Q3c) Write the syntax and explain use of following methods of JavaScript
Timing Event
i) setTimeout()
ii) setInterval()
i) setTimeout(): Executes a function once after a specific delay (in milliseconds).
Syntax: setTimeout(function, milliseconds);
Example:
setTimeout(() => alert("Hello after 3 seconds"), 3000);

ii) setInterval(): Executes a function repeatedly at specified intervals.


Syntax: setInterval(function, milliseconds);
Example:
setInterval(() => console.log("Repeats every 2 seconds"), 2000);

Q4a) Explain the syntax of opening window.


Syntax:
window.open(URL, name, features, replace);

- URL: URL of the page to open


- name: Target window (_blank, _self, etc.)
- features: Comma-separated list like width, height, resizable, scrollbars
- replace: Optional boolean

Example:
window.open("https://example.com", "_blank", "width=600,height=400");

Q4b) Explain how to create cookies in JavaScript.


Cookies are created by assigning a string to document.cookie.
document.cookie = "key=value; expires=date; path=/";

Example:
document.cookie = "username=Jane; expires=Sat, 31 Dec 2025 12:00:00 UTC; path=/";

Q5a) What are the attributes used to set position of window.


Attributes used in `window.open()` to set window position:
1. left – Distance from left edge of screen.
2. top – Distance from top edge of screen.
3. width – Width of the window.
4. height – Height of the window.
Example:
window.open("https://example.com", "_blank",
"left=200,top=100,width=400,height=300");

Q5b) Write a function that prompts the user for a color and uses what
they select to set the background color of the new webpage opened.
<script>
function changeBackgroundColor() {
let color = prompt("Enter your favorite color:");
let newWin = window.open("", "_blank", "width=500,height=400");
newWin.document.write(`<body
style="background-color:${color};"><h1>Welcome!</h1></body>`);
}
</script>

Client-Side Scripting (JavaScript) –


Frames, Regex, Rollover, and Validation
a) Define frame.
A frame is a section of a web browser window that can display a separate HTML document.
Frames are used to divide the browser window into multiple, independently scrollable
sections. In HTML, frames were created using the <frameset> and <frame> tags, but modern
HTML uses the <iframe> tag for embedding one HTML document within another.

b) Define term Regular expression.


A Regular Expression (RegEx) is a sequence of characters that defines a search pattern. In
JavaScript, it is used for pattern matching and text processing, such as form validation,
searching, and replacing text.

b) Explain any four methods used in Regular expression.


1. test(): Tests if a pattern matches in a string and returns true or false.
Example: /abc/.test('abc123'); // returns true

2. exec(): Executes a search for a match in a string and returns an array of information.
Example: /\d+/.exec('Year 2025'); // returns ['2025']

3. match(): Searches a string for a match against a regular expression.


Example: 'abc123'.match(/\d+/); // returns ['123']
4. replace(): Replaces matched substring with another string.
Example: 'abc123'.replace(/\d+/, '***'); // returns 'abc***'

c) State and explain the process to make the rollover more efficient.
To make rollover more efficient:
1. Preload the images to avoid delays.
2. Use onmouseover and onmouseout events to switch images.
3. Use CSS and JavaScript together to enhance performance and reduce flicker.

Benefits: Better user experience and quicker image transitions.

d) Write a simple JavaScript to create child window and accessing elements of


another child window.
<script>
function openChild() {
let child = window.open('', '', 'width=300,height=200');
child.document.write('<input type="text" id="msg" value="Hello from child!">');
setTimeout(() => {
alert(child.document.getElementById('msg').value);
}, 1000);
}
</script>

a) Write a javascript in which when user rollover the name of fruit, the
corresponding image should be display.
<html><body>
<p onmouseover="document.getElementById('img').src='apple.jpg'">Apple</p>
<p onmouseover="document.getElementById('img').src='banana.jpg'">Banana</p>
<img id='img' src='' width='100'>
</body></html>

b) Explain FrameSet/iFrame tag along with attributes used in it.


<frameset> is used to divide the browser window into multiple frames. Attributes: rows,
cols.
Example:
<frameset cols='50%,50%'>
<frame src='left.html'>
<frame src='right.html'>
</frameset>

<iframe> embeds a document inside another. Attributes: src, width, height, frameborder.
Example:
<iframe src='page.html' width='300' height='200' frameborder='0'></iframe>
c) State the use of rollover & write a method used most commonly during
rollover.
Rollover is used to change an element’s appearance or image when a user hovers the mouse
over it.

Most commonly used method: onmouseover and onmouseout.


Example:
<img src='off.jpg' onmouseover="this.src='on.jpg'" onmouseout="this.src='off.jpg'">

d) Write a javascript function to check whether a given value is valid IP or Not.


<script>
function validateIP(ip) {
const pattern = /^(\d{1,3}\.){3}\d{1,3}$/;
return pattern.test(ip);
}
</script>

c) Write webpage that accepts username and aadharcard as input texts...


<html><body>
<form>
Username: <input type='text' id='username'><br>
Aadhar: <input type='text' id='aadhar' onblur='validate()'><br>
<span id='msg'></span>
</form>
<script>
function validate() {
let a = document.getElementById('aadhar').value;
let pattern = /^\d{4}[.-]\d{4}[.-]\d{4}$/;
document.getElementById('msg').innerText = pattern.test(a) ? 'Valid' : 'Invalid';
}
</script></body></html>

d) Write a script for creating following frame structure:


<frameset rows='20%,80%'>
<frame src='top.html' name='frame1'>
<frameset cols='33%,33%,34%'>
<frame src='left.html' name='frame2'>
<frame src='middle.html' name='frame3'>
<frame src='right.html' name='frame4'>
</frameset>
</frameset>
b) What is rollover?
Rollover is an effect that occurs when the user hovers over an element (like an image or
button). It is commonly used in navigation menus to visually indicate the interactive
element. It is typically implemented using JavaScript or CSS events like onmouseover.

a) Explain how to set the frame border invisible. Write a JavaScript to do border
invisible.
To make the frame border invisible, use frameborder='0' and style='border:none'.

Example:
<iframe src='page.html' width='300' height='200' frameborder='0'
style='border:none;'></iframe>

b) Explain any four commonly used method in regular expression.


1. test()
2. exec()
3. match()
4. replace()

These methods help in testing, extracting, matching, and replacing string patterns using
regular expressions.

a) What are the attributes are used to set position of window.


Attributes to set position: left, top, width, height

Example:
window.open('url', '_blank', 'left=200,top=100,width=300,height=200');

b) Write a function that prompts the user for a color...


<script>
function promptColor() {
let color = prompt('Enter color:');
let win = window.open('', '', 'width=400,height=300');
win.document.write(`<body
style='background-color:${color};'><h1>Color</h1></body>`);
}
</script>

a) Construct regular expression for validating phone number in (nnn)-nnnn-


nnnn OR nnn.nnnn.nnnn format.
let pattern = /^\(\d{3}\)-\d{4}-\d{4}$|^\d{3}\.\d{4}\.\d{4}$/;

Examples:
(123)-4567-8901 => valid
123.4567.8901 => valid

Client-Side Scripting (JavaScript) –


Banners, Menus, Scrolling, and
Slideshow
a) What is banner id?
A banner ID refers to a unique identifier used in JavaScript or HTML to reference and
control a banner element, usually an image or text banner on a webpage. It allows
developers to manipulate the content dynamically through scripts, such as rotating ads or
displaying different images.

b) State the method to put message in web browser.


In JavaScript, you can put a message in the web browser using:
1. `alert('Your message')` – displays a popup alert box.
2. `document.write('Your message')` – writes directly into the HTML document.
3. `console.log('Your message')` – logs the message to the browser console.
4. `status` bar message (deprecated in modern browsers): `window.status = 'Your
message';`

c) Define dynamic menu.


A dynamic menu is a menu system that changes in response to user interaction or
programmatic conditions. It can be created using JavaScript to display submenus, change
styles, or load different menu items based on user role, time, or selection.

a) Explain sliding menu and scrollable menu.


Sliding Menu: A menu that slides in and out from the side or top/bottom of the page. It is
often used in mobile or responsive designs.

Scrollable Menu: A menu that stays fixed in size but allows scrolling within its container
when there are too many items to fit at once.

b) Write JavaScript programs that create a scrolling text on the status line of a
window.
<script>
var msg = "Welcome to JavaScript! ";
var pos = 0;
function scrollMsg() {
window.status = msg.substring(pos) + msg.substring(0, pos);
pos = (pos + 1) % msg.length;
setTimeout(scrollMsg, 200);
}
scrollMsg();
</script>

c) Write a JavaScript program to create rollover effect for three images.


<img src='img1.jpg' onmouseover="this.src='img1_hover.jpg'"
onmouseout="this.src='img1.jpg'">
<img src='img2.jpg' onmouseover="this.src='img2_hover.jpg'"
onmouseout="this.src='img2.jpg'">
<img src='img3.jpg' onmouseover="this.src='img3_hover.jpg'"
onmouseout="this.src='img3.jpg'">

c) Write the name of method to create slideshow.


The most common method to create a slideshow in JavaScript is using the `setInterval()`
function to periodically change images.

Example: `setInterval(changeSlide, 3000);`

a) Write a program that disables the right click of mouse button and displays
the message.
<script>
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
alert('Right click button is disabled');
});
</script>

b) Develop the JavaScript program to create rotating banner ads with URL links.
<script>
var ads = [
{img: 'ad1.jpg', link: 'http://site1.com'},
{img: 'ad2.jpg', link: 'http://site2.com'},
{img: 'ad3.jpg', link: 'http://site3.com'}
];
var i = 0;
function rotateAds() {
var ad = ads[i];
document.getElementById('banner').innerHTML = `<a href='${ad.link}'><img src='$
{ad.img}'></a>`;
i = (i + 1) % ads.length;
setTimeout(rotateAds, 3000);
}
</script>
<div id='banner'></div>
<script>rotateAds();</script>

c) List ways of protecting your webpage and describe any one of them.
1. Disable right-click and keyboard shortcuts.
2. Minify and obfuscate JavaScript.
3. Use HTTPS to secure data.
4. Set up authentication and authorization.

Example: Disabling right-click prevents users from easily copying content.

b) Construct regular expression for mobile number.


var pattern = /^[6-9]\d{9}$/;

This regex validates Indian mobile numbers starting with 6 to 9 and having a total of 10
digits.

c) Define menu and its types.


A menu is a navigation structure in a website that provides links to different sections or
pages. Types of menus include:
1. Static Menu
2. Dynamic Menu
3. Drop-down Menu
4. Pull-down Menu
5. Sliding Menu

a) Write a JavaScript to create a simple pull down menu.


<select onchange="alert('You selected: ' + this.value)">
<option value=''>--Select--</option>
<option value='Fruit'>Fruit</option>
<option value='Flower'>Flower</option>
<option value='Color'>Color</option>
</select>

c) Write JavaScript program that creates a scrolling text on the status line of a
window.
<script>
var msg = 'Scrolling Status Text - '; var pos = 0;
function scrollStatus() {
window.status = msg.substring(pos) + msg.substring(0, pos);
pos = (pos + 1) % msg.length;
setTimeout(scrollStatus, 200);
}
scrollStatus();
</script>

a) Develop a JavaScript Program to Create Rotating Banner Ads with URL Links.
<script>
var ads = [
{img: '1.jpg', url: 'http://link1.com'},
{img: '2.jpg', url: 'http://link2.com'},
{img: '3.jpg', url: 'http://link3.com'}
];
var index = 0;
function showBanner() {
var ad = ads[index];
document.getElementById('bannerAd').innerHTML = `<a href='${ad.url}'><img src='$
{ad.img}' width='300'></a>`;
index = (index + 1) % ads.length;
setTimeout(showBanner, 3000);
}
</script>
<div id='bannerAd'></div>
<script>showBanner();</script>

b) Create a slideshow with the group of four images...


<html>
<body>
<img id='slide' src='img1.jpg' width='300'>
<br>
<button onclick='prev()'>Previous</button>
<button onclick='next()'>Next</button>
<script>
var images = ['img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg'];
var i = 0;
function show() {
document.getElementById('slide').src = images[i];
}
function next() {
i = (i + 1) % images.length; show();
}
function prev() {
i = (i - 1 + images.length) % images.length; show();
}
</script>
</body>
</html>

You might also like