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

CSS Summer 22

Model Ans Paper
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

CSS Summer 22

Model Ans Paper
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

CSS Summer 22 Question Paper

1. Attempt any FIVE of the following : 10

(a) State the features of Javascript.


Ans.Features of Java script
1. JavaScript is a object-based scripting language.
2. Giving the user more control over the browser.
3. It Handling dates and time.
4. It Detecting the user's browser and OS,
5. It is light weighted.
6. Client – Side Technology
7. JavaScript is a scripting language and it is not java.
8. JavaScript is interpreter based scripting language.
9. JavaScript is case sensitive.
10. JavaScript is object based language as it provides predefined objects.
11. Every statement in javascript must be terminated with semicolon (;).
12. Most of the javascript control statements syntax is same as syntax of
control statements in C language.
13. An important part of JavaScript is the ability to create new functions
within scripts. Declare a function in JavaScript
using function keyword.

(b) Differentiate between bession cookies and persistent cookies.


Ans.
Feature Session Cookies Persistent Cookies
Lifespan Erased when the browser closes Remains on the user’s device until they
expire or are manually deleted
Purpose Remembers user actions and Remembers user preferences and login
preferences during a browsing information across multiple sessions
session
Performance Enhances website performance by Aids in website performance optimization
Improvemen reducing server requests by reducing server requests
t
Storage Doesn’t occupy much space May occupy storage space over time
space
Privacy Can potentially track users, leading Used for targeted advertising and
Concerns to privacy concerns tracking, potentially raising privacy
concerns
(c) Write a javascript program to check whether entered number is prime or not.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prime Number Checker</title>
</head>
<body>

<h1>Prime Number Checker</h1>

<label for="numberInput">Enter a number:</label>


<input type="number" id="numberInput">
<button onclick="checkPrime()">Check if Prime</button>

<p id="result"></p>

<script>
function checkPrime() {
// Get the entered number
let number = parseInt(document.getElementById("numberInput").value);
let isPrime = true;

// Edge case for numbers less than or equal to 1


if (number <= 1) {
isPrime = false;
} else {
// Check divisibility from 2 up to the square root of the number
for (let i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) {
isPrime = false;
break;
}
}
}

// Display the result


if (isPrime) {
document.getElementById("result").innerHTML = number + " is a prime number.";
} else {
document.getElementById("result").innerHTML = number + " is not a prime number.";
}
}
</script>

</body>
</html>

(d) Explain following form events :


(i) onmouseup
(ii) onblur
Ans.1. onmouseup Event
The onmouseup event is triggered when the mouse button is released after being pressed down on an
element. This event typically occurs after the mousedown event (when the mouse button is pressed) and
before the click event (which occurs when the mouse button is pressed and released).
Key Points:
 It applies to most HTML elements, especially interactive ones like buttons, input fields, or any
clickable components.
 It is often used for actions like submitting forms, performing custom actions, or releasing dragged
elements in drag-and-drop interfaces.
Example Usage:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>onmouseup Event Example</title>
</head>
<body>

<button id="myButton">Click Me!</button>


<p id="output"></p>

<script>
document.getElementById("myButton").addEventListener("mouseup", function() {
document.getElementById("output").innerHTML = "Mouse button released!";
});
</script>

</body>
</html>
2. onblur Event
The onblur event is triggered when an element loses focus. This is commonly used for form elements
(like text inputs, textareas, or dropdowns) to detect when the user has finished interacting with a field and
moved focus to another element or clicked elsewhere on the page.
Key Points:
 The onblur event is typically used for input validation or triggering an action when the user
moves away from a form field.
 It can be useful in scenarios like checking for required fields, validating email formats, or saving
data when the user leaves a field.
Example Usage:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>onblur Event Example</title>
</head>
<body>

<label for="emailInput">Enter your email:</label>


<input type="text" id="emailInput">
<p id="message"></p>

<script>
document.getElementById("emailInput").addEventListener("blur", function() {
let emailValue = document.getElementById("emailInput").value;

// Simple email validation (just checking if it contains '@')


if (!emailValue.includes("@")) {
document.getElementById("message").innerHTML = "Please enter a valid email.";
document.getElementById("message").style.color = "red";
} else {
document.getElementById("message").innerHTML = "Email looks good!";
document.getElementById("message").style.color = "green";
}
});
</script>

</body>
</html>

(e) Write a javascript program to changing the contents of a window.


Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Content Example</title>
<script>
function changeContent() {
document.getElementById("content").innerHTML = "<h2>Content Changed!</h2><p>The
content of this window has been successfully updated using JavaScript.</p>";
}
</script>
</head>
<body>
<h1>Original Window Content</h1>
<div id="content">
<p>This is the original content of the window.</p>
</div>
<button onclick="changeContent()">Change Content</button>
</body>
</html>

(f) Explain frame works of javascript and its application.


Ans.Frameworks of JavaScript:
1. ReactJs
React is based on a reusable component. Simply put, these are code blocks that can be
classified as either classes or functions. Each component represents a specific part of a
page, such as a logo, a button, or an input box. The parameters they use are called props,
which stands for properties.
Applications:
React is a JavaScript library developed by Facebook which, among other things, was used
to build Instagram.com.
2. Angular
Google operates this framework and is designed to use it to develop a Single Page
Application (SPA). This development framework is known primarily because it gives
developers the best conditions to combine JavaScript with HTML and CSS. Google
operates this framework and is designed to use it to develop a Single Page Application
(SPA). This development framework is known primarily because it gives developers the
best conditions to combine JavaScript with HTML and CSS.
Applications:
Microsoft Office ,Gmail, Forbes, PayPal, Grasshopper, Samsung, Delta
3. Vue.js
Vue is an open-source JavaScript framework for creating a creative UI. The integration
with Vue in projects using other JavaScript libraries is simplified because it is designed to
be adaptable.
Application:
VueJS is primarily used to build web interfaces and one-page applications. It can also
be applied to both desktop and mobile app development.
4. jQuery
It is a cross-platform JavaScript library designed to simplify HTML client-side scripting.
You can use the jQuery API to handle, animate, and manipulate an event in an HTML
document, also known as DOM. Also, jQuery is used with Angular and React App building
tools.
Applications:
1. JQuery can be used to develop Ajax based applications.
2. It can be used to make code simple, concise and reusable.
3. It simplifies the process of traversal of HTML DOM tree.
4. It can also handle events, perform animation and add ajax support in web applications.

(g) Write a javascript syntax to accessing elements of another child window.


Ans.
// Open a new child window
var childWindow = window.open("child.html", "Child Window", "width=400,height=400");
// Access elements of the child window
// Make sure to access the elements only after the child window has fully loaded
childWindow.onload = function() {
var childElement = childWindow.document.getElementById("childElementId");
console.log(childElement); // Do something with the element, e.g., change its value or style
};

2.Attempt any THREE of the following : 12

(a) Write a javascript program to validate user accounts for multiple set of user ID and password
(using swith case statement).
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Account Validation</title>
</head>
<body>

<h1>User Account Validation</h1>

<label for="userIdInput">User ID:</label>


<input type="text" id="userIdInput" placeholder="Enter User ID">
<br><br>

<label for="passwordInput">Password:</label>
<input type="password" id="passwordInput" placeholder="Enter Password">
<br><br>
<button onclick="validateUser()">Login</button>

<p id="result"></p>

<script>
function validateUser() {
// Get user input values
var userId = document.getElementById("userIdInput").value;
var password = document.getElementById("passwordInput").value;
var result = "";

// Switch case to validate multiple user ID and password sets


switch (userId) {
case "user1":
if (password === "password1") {
result = "Welcome, User 1!";
} else {
result = "Invalid password for User 1.";
}
break;

case "user2":
if (password === "password2") {
result = "Welcome, User 2!";
} else {
result = "Invalid password for User 2.";
}
break;

case "admin":
if (password === "adminPass") {
result = "Welcome, Admin!";
} else {
result = "Invalid password for Admin.";
}
break;

default:
result = "Invalid User ID.";
break;
}

// Display the result


document.getElementById("result").innerHTML = result;
}
</script>

</body>
</html>

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


Ans.
Feature concat() join()
Purpose Combines two or more arrays Joins all elements of an array
into a string
Returns A new array A single string
Modifies original array? No No
Usage example arr1.concat(arr2) arr.join('-')
Parameter(s) One or more arrays or values to A string to separate each array
concatenate element
Default separator Not applicable , (comma)
Can concatenate Yes No
primitive values?
Can concatenate Yes, pass multiple arrays as No, only joins elements of a
multiple arrays? arguments single array
(c) Write a javascript program to demonstrate java intrinsic function.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Intrinsic Functions in JavaScript</title>
<script>
function demoIntrinsicFunctions() {
// Using parseInt() to convert string to integer
let num1 = parseInt("123");
document.getElementById("parseIntDemo").innerHTML = "parseInt('123') = " + num1;

// Using parseFloat() to convert string to floating-point number


let num2 = parseFloat("123.456");
document.getElementById("parseFloatDemo").innerHTML = "parseFloat('123.456') = " + num2;

// Using isNaN() to check if a value is Not-A-Number


let checkNaN = isNaN("Hello");
document.getElementById("isNaNDemo").innerHTML = "isNaN('Hello') = " + checkNaN;
// Using Math.sqrt() to calculate the square root of a number
let sqrtValue = Math.sqrt(64);
document.getElementById("sqrtDemo").innerHTML = "Math.sqrt(64) = " + sqrtValue;

// Using Math.random() to generate a random number between 0 and 1


let randomValue = Math.random();
document.getElementById("randomDemo").innerHTML = "Math.random() = " + randomValue;

// Using Date() to get the current date and time


let currentDate = new Date();
document.getElementById("dateDemo").innerHTML = "Current Date and Time: " + currentDate;
}
</script>
</head>
<body onload="demoIntrinsicFunctions()">

<h1>JavaScript Intrinsic Functions Demonstration</h1>


<p id="parseIntDemo"></p>
<p id="parseFloatDemo"></p>
<p id="isNaNDemo"></p>
<p id="sqrtDemo"></p>
<p id="randomDemo"></p>
<p id="dateDemo"></p>
</body>
</html>

(d) Design a webpage that displays a form that contains an input for user name and password. User
is prompted to enter the input user name and password and password become value of the cookies.
Write the javascript function for storing the cookies.
Ans.
<html>
<head>
<script>
function storeCookie()
{
var pwd = document.getElementById('pwd').value
document.cookie = "Password=" + pwd + ";"
alert("Cookie Stored\n"+document.cookie);
}
</script>
</head>
<body>
<form name="myForm">
Enter Username <input type="text" id="uname"/><br/>
Enter Password <input type="password" id="pwd"/><br/>
<input type="button" value="Submit" onclick="storeCookie()"/>
<p id="panel"></p>
</form>
</body>
</html>

3.Attempt any THREE of the following : 12

(a) Write a javascript program to create read, update and delete cookies.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie Management</title>
<script>
// Function to create or update a cookie
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000)); // Set expiration date in milliseconds
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
alert("Cookie " + cname + " has been set.");
}

// Function to read a specific cookie


function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}

// Function to check if a cookie exists


function checkCookie(cname) {
let cookie = getCookie(cname);
if (cookie != "") {
alert("Cookie found: " + cname + "=" + cookie);
} else {
alert("Cookie " + cname + " not found.");
}
}

// Function to delete a cookie


function deleteCookie(cname) {
setCookie(cname, "", -1); // Setting the expiration date in the past deletes the cookie
alert("Cookie " + cname + " has been deleted.");
}
</script>
</head>
<body>

<h2>Cookie Management Program</h2>


<div>
<label for="cookieName">Cookie Name:</label><br>
<input type="text" id="cookieName"><br><br>

<label for="cookieValue">Cookie Value:</label><br>


<input type="text" id="cookieValue"><br><br>

<label for="expiryDays">Expiry Days:</label><br>


<input type="number" id="expiryDays" value="1"><br><br>

<button onclick="setCookie(document.getElementById('cookieName').value,
document.getElementById('cookieValue').value,
document.getElementById('expiryDays').value)">Create/Update Cookie</button>
<button onclick="checkCookie(document.getElementById('cookieName').value)">Read
Cookie</button>
<button onclick="deleteCookie(document.getElementById('cookieName').value)">Delete
Cookie</button>
</div>

<h3>Instructions:</h3>
<p>1. Enter a cookie name, value, and expiry days, then click **Create/Update Cookie** to set the
cookie.</p>
<p>2. Enter the cookie name and click **Read Cookie** to retrieve the cookie value.</p>
<p>3. Enter the cookie name and click **Delete Cookie** to remove the cookie.</p>
</body>
</html>

(b) Write a javascript program to link banner advertisements to different URLs.


Ans.
<html>
<head>
<title>Link Banner Ads</title>
<script language="Javascript" type="text/javascript">
Banners = new Array('1.jpg','2.jpg','3.jpg')
BannerLink = new Array(
'google.com/','vpt.edu.in/', 'msbte.org.in/');
CurrentBanner = 0;
NumOfBanners = Banners.length;
function LinkBanner()
{
document.location.href =
"http://www." + BannerLink[CurrentBanner];
}
function DisplayBanners() {
if (document.images) {
CurrentBanner++
if (CurrentBanner == NumOfBanners) {
CurrentBanner = 0
}
document.RotateBanner.src= Banners[CurrentBanner]
setTimeout("DisplayBanners()",1000)
}
}
</script>
</head>
<body onload="DisplayBanners()" >
<center>
<a href="javascript: LinkBanner()"><img src="1.jpg"
width="400" height="75" name="RotateBanner" /></a>
</center>
</body> </html>

(c) Write a javascript program to calculate add, sub, multiplication and division of two number
(input from user). Form should contain two text boxes to input numbers of four buttons for
addition, subtraction, multiplication and division.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
</head>
<body>

<h1>Simple Calculator</h1>

<!-- Input fields for numbers -->


<label for="num1">Number 1:</label>
<input type="number" id="num1" placeholder="Enter first number">
<br><br>

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


<input type="number" id="num2" placeholder="Enter second number">
<br><br>

<!-- Buttons for operations -->


<button onclick="calculate('add')">Add</button>
<button onclick="calculate('subtract')">Subtract</button>
<button onclick="calculate('multiply')">Multiply</button>
<button onclick="calculate('divide')">Divide</button>

<h3>Result: <span id="result"></span></h3>

<script>
function calculate(operation) {
// Get the input values from the textboxes
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
var result;

// Check if both numbers are entered


if (isNaN(num1) || isNaN(num2)) {
alert("Please enter both numbers.");
return;
}

// Perform the selected operation


switch (operation) {
case 'add':
result = num1 + num2;
break;
case 'subtract':
result = num1 - num2;
break;
case 'multiply':
result = num1 * num2;
break;
case 'divide':
if (num2 !== 0) {
result = num1 / num2;
} else {
alert("Division by zero is not allowed.");
return;
}
break;
default:
result = "Invalid operation.";
}

// Display the result


document.getElementById("result").innerText = result;
}
</script>

</body>
</html>

(d) State what is regular expression. Explain its meaning with the help of a suitable example.
Ans.Regular Expression:
A regular expression is very similar to a mathematical expression, except a
regular expression tells the browser how to manipulate text rather than numbers
by using special symbols as operators.
Example:
<html>
<body>
<script>
function myFunction() {
// input string
var str = "Good Morning!";
// searching string with modifier i
var n = str.search(/Morning/i);
document.write(n + '<br>');
// searching string without modifier i
var n = str.search(/Morning/);
document.write(n);
}
myFunction();
</script>
</body>
</html>

4.Attempt any THREE of the following : 12

(a) Differentiate between For-loop and For-in loop.


Ans.
Feature For Loop For-In Loop
Purpose Iterates over the elements of an array or other Iterates over the enumerable
collections based on index properties of an object
Syntax for (initialization; condition; increment) for (var property in object)
Iteration Arrays, strings, any collections with a defined Objects (specifically their
target number of items enumerable properties)
Control Can define and manipulate control variables Uses a property variable to
variables access object properties
Performan Generally faster for arrays and collections Slower compared to for loop due
ce to property lookup
Best use When you need to iterate a specific number of When you need to access all
case times or need the index properties of an object
Compatibil Works with any iterable or array-like objects Works with any objects with
ity enumerable properties
Can skip Yes, by using continue or custom conditions No, iterates over all enumerable
elements? within the loop properties
(b) Write a javascript function that accepts a string as a parameter and find the length of the string.
Ans.
function findStringLength(str) {
// Check if the input is a valid string
if (typeof str === 'string') {
// Return the length of the string
return str.length;
} else {
return "Input is not a valid string.";
}
}
// Example usage:
let userInput = "Hello, World!";
let lengthOfString = findStringLength(userInput);
console.log("The length of the string is: " + lengthOfString);

(c) Write a javascript program to validate email ID of the user using regular expression.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Email Validation</title>
<script>
// Function to validate email using a regular expression
function validateEmail() {
const email = document.getElementById("email").value;
// Regular expression for validating email
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

// Test the email against the pattern


if (emailPattern.test(email)) {
alert("Valid email address.");
} else {
alert("Invalid email address. Please enter a valid email.");
}
}
</script>
</head>
<body>

<h2>Email Validation Form</h2>


<form onsubmit="event.preventDefault(); validateEmail();">
<label for="email">Email:</label><br>
<input type="text" id="email" name="email" required><br><br>
<input type="submit" value="Validate Email">
</form>

</body>
</html>

(d)Write a javascript program to design HTML page with books information in abular format, use
rollovers to display the discount information.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Book Information</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
.discount {
display: none;
position: absolute;
background-color: yellow;
padding: 5px;
border: 1px solid #ccc;
border-radius: 4px;
z-index: 10;
}
</style>
</head>
<body>

<h1>Book Information</h1>
<table>
<thead>
<tr>
<th>Book Title</th>
<th>Author</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td onmouseover="showDiscount(event, '10% Off!')"
onmouseout="hideDiscount()">JavaScript: The Good Parts</td>
<td>Douglas Crockford</td>
<td>$29.99</td>
</tr>
<tr>
<td onmouseover="showDiscount(event, '15% Off!')" onmouseout="hideDiscount()">Clean
Code</td>
<td>Robert C. Martin</td>
<td>$34.99</td>
</tr>
<tr>
<td onmouseover="showDiscount(event, '20% Off!')" onmouseout="hideDiscount()">Eloquent
JavaScript</td>
<td>Marijn Haverbeke</td>
<td>$39.99</td>
</tr>
<tr>
<td onmouseover="showDiscount(event, '5% Off!')" onmouseout="hideDiscount()">The
Pragmatic Programmer</td>
<td>Andrew Hunt, David Thomas</td>
<td>$49.99</td>
</tr>
</tbody>
</table>

<div id="discountTooltip" class="discount"></div>

<script>
function showDiscount(event, discount) {
const tooltip = document.getElementById("discountTooltip");
tooltip.innerText = discount; // Set the discount text
tooltip.style.left = event.pageX + 'px'; // Position tooltip
tooltip.style.top = event.pageY + 'px'; // Position tooltip
tooltip.style.display = 'block'; // Show tooltip
}

function hideDiscount() {
const tooltip = document.getElementById("discountTooltip");
tooltip.style.display = 'none'; // Hide tooltip
}
</script>

</body>
</html>

(e)List ways of protecting your webpage and describe any one of them.
Ans.Ways of protecting Web Page:
1)Hiding your source code
2)Disabling the right MouseButton
3) Hiding JavaScript
4) Concealing E-mail address.
1) Hiding your source code
The source code for your web page—including your JavaScript—is stored in the
cache, the part of computer memory where the browser stores web pages that
were requested by the visitor. A sophisticated visitor can access the cache and
thereby gain access to the web page source code.
However, you can place obstacles in the way of a potential peeker. First, you can
disable use of the right mouse button on your site so the visitor can't access the
View Source menu option on the context menu. This hides both your HTML code
and your JavaScript from the visitor.
Nevertheless, the visitor can still use the View menu's Source option to display
your source code. In addition, you can store your JavaScript on your web server
instead of building it into your web page. The browser calls the JavaScript from
the web server when it is needed by your web page.
Using this method, the JavaScript isn't visible to the visitor, even if the visitor
views the source code for the web page.
2)Disabling the right MouseButton
The following example shows you how to disable the visitor's right mouse button
while the browser displays your web page. All the action occurs in the JavaScript
that is defined in the <head> tag of the web page.
The JavaScript begins by defining the BreakInDetected() function. This function
is called any time the visitor clicks the right mouse button while the web page is
displayed. It displays a security violation message in a dialog box whenever a
visitor clicks the right mouse button
The BreakInDetected() function is called if the visitor clicks any button other
than the left mouse button.
Example:
<html>
<head>
<title>Lockout Right Mouse Button</title>
<script language=JavaScript>
function BreakInDetected(){
alert('Security Violation')
return false
}
function NetscapeBrowser(e){
if (document.layers||
document.getElementById&&!document.all){
if (e.which==2||e.which==3){
BreakInDetected()
return false
}
}
}
function InternetExploreBrowser(){
if (event.button==2){
BreakInDetected()
return false
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN)
document.onmousedown=NetscapeBrowser()
}
else if (document.all&&!document.getElementById){
document.onmousedown=InternetExploreBrowser()
}
document.oncontextmenu=new Function(
"BreakInDetected();return false")
</script>
</head>
<body>
<table width="100%" border=0>
<tbody>
<tr vAlign=top>
<td width=50>
<a>
<ing height=92 src="rose.jpg"
width=70 border=0
onmouseover="src='rose1.jpg'"
onmouseout="src='rose.jpg'">
</a>
</td>
<td>
<img height=1 src="" width=10>
</td>
<td>
<a>
<cTypeface:Bold><u> Rose Flower</U></b>
</a>
</font><font face="arial, helvetica, sans-serif"
size=-1><BR>Rose Flower
</td>
</tr>
</tbody>
</table>
</body>
</html>
3) Hiding JavaScript
You can hide your JavaScript from a visitor by storing it in an external fi le on
your web server. The external fi le should have the .js fi le extension. The browser
then calls the external file whenever the browser encounters a JavaScript element
in the web page. If you look at the source code for the web page, you'll see
reference to the external .js fi le, but you won't see the source code for the
JavaScript.
The next example shows how to create and use an external JavaScript file. First
you must tell the browser that the content of the JavaScript is located in an
external
file on the web server rather than built into the web page. You do this by assigning
the fi le name that contains the JavaScripts to the src attribute of the <script>
tag, as shown here:
<script src="MyJavaScripts.js"
language="Javascript" type="text/javascript">
Next, you need to defi ne empty functions for each function that you define in the
external JavaScript fi le.
<html >
<head>
<title>Using External JavaScript File</title>
<script src="myJavaScript.js" language="Javascript" type="text/javascript">
function OpenNewWindow(book) {
}
</script>
</head>
<body>
<tablewidth="100%" border=0>
<tbody>
<tr vAlign=top>
<td width=50>
<a>
<img height=92 src="rose.jpg" width=70 border=0 name='cover'>
</a>
</td>
<td>
<img height=1 src="" width=10>
</td>
<td>
<a onmouseover="OpenNewWindow(1)" onmouseout="MyWindow.close()">
<b><u>Rose </u></b>
</a>
<br>
<a onmouseover="OpenNewWindow(2)" onmouseout="MyWindow.close()">
<b><u>Sunflower</U></b>
</a>
<br>
<A onmouseover="OpenNewWindow(3)" onmouseout="MyWindow.close()">
<b><u>Jasmine </u></b>
</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
The final step is to create the external JavaScript fi le. You do this by placing all
function definitions into a new fi le and then saving the fi le using the .js
extension.
MyJavaScript.js file:
function OpenNewWindow(book) {
if (book== 1)
{
document.cover.src='rose.jpg'
MyWindow = window.open('', 'myAdWin', 'titlebar=0 status=0, toolbar=0,
location=0, menubar=0, directories=0, resizable=0, height=50,
width=150,left=500,top=400')
MyWindow.document.write( 'Rose flower')
}
if (book== 2)
{
document.cover.src='sunflower.jpeg'
MyWindow = window.open('', 'myAdWin', 'titlebar=0 status=0, toolbar=0,
location=0, menubar=0, directories=0, resizable=0, height=50,
width=150,left=500,top=500')
MyWindow.document.write( 'sunflower flower')
}
if (book== 3)
{
document.cover.src='jasmine.gif'
MyWindow = window.open('', 'myAdWin', 'titlebar=0
status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=0,
height=50,
width=150,left=500,top=600')
MyWindow.document.write( 'Jasmine Flower')
}
}
After you create the external JavaScript fi le, defi ne empty functions for each
function that is contained in the external JavaScript fi le, and reference the
external
JavaScript fi le in the src attribute of the <script> tag, you're all set.
4) Concealing E-mail address:
Many of us have endured spam at some point and have probably blamed every
merchant we ever patronized for selling our e-mail address to spammers. While
e-mail addresses are commodities, it's likely that we ourselves are the culprits
who invited spammers to steal our e-mail addresses.
Here's what happens: Some spammers create programs called bots that surf the
Net looking for e-mail addresses that are embedded into web pages, such as those
placed there by developers to enable visitors to contact them. The bots then strip
these e-mail addresses from the web page and store them for use in a spam attack.
This technique places developers between a rock and a hard place. If they place
their e-mail addresses on the web page, they might get slammed by spammers. If
they don't display their e-mail addresses, visitors will not be able to get in touch
with the developers.
The solution to this common problem is to conceal your e-mail address in the
source code of your web page so that bots can't fi nd it but so that it still appears
on the web page. Typically, bots identify e-mail addresses in two ways: by the
mailto: attribute that tells the browser the e-mail address to use when the visitor
wants to respond to the web page, and by the @ sign that is required of all e-mail
addresses. Your job is to confuse the bots by using a JavaScript to generate the
e-mail address dynamically. However, you'll still need to conceal the e-mail
address in your JavaScript, unless the JavaScript is contained in an external
JavaScript file, because a bot can easily recognize the mailto: attribute and the @
sign in a JavaScript.
Bots can also easily recognize when an external fi le is referenced. To conceal an
e-mail address, you need to create strings that contain part of the e-mail address
and then build a JavaScript that assembles those strings into the e-mail address,
which is then written to the web page.
The following example illustrates one of many ways to conceal an e-mail address.
It also shows you how to write the subject line of the e-mail. We begin by
creating four strings:
• The first string contains the addressee and the domain along with symbols &, *,
and _ (underscore) to confuse the bot.
• The second and third strings contain portions of the mailto: attribute name.
Remember that the bot is likely looking for mailto:.
• The fourth string contains the subject line. As you'll recall from your HTML
training, you can generate the TO, CC, BCC, subject, and body of an e-mail from
within a web page.
You then use these four strings to build the e-mail address. This process starts by
using the replace() method of the string object to replace the & with the @ sign
and the * with a period (.). The underscores are replaced with nothing, which is
the
same as simply removing the underscores from the string.
All the strings are then concatenated and assigned to the variable b, which is then
assigned the location attribute of the window object. This calls the e-mail program
on the visitor's computer and populates the TO and Subject lines with the strings
generated by the JavaScript.
<html>
<head>
<title>Conceal Email Address</title>
<script>
function CreateEmailAddress(){
var x = manish*c_o_m'
var y = 'mai'
var z = 'lto'
var s = '?subject=Customer Inquiry'
x = x.replace('&','@')
x = x.replace('*','.')
x = x.replace('_','')
x = x.replace('_','')
var b = y + z +':'+ x + s
window.location=b
}
-->
</script>
</head>
<body>
<input type="button" value="Help"
onclick="CreateEmailAddress()">
</body>
</html>

5.Attempt any TWO of the following : 12

(a) Write a javascript to checks whether a passed string is palindrome or not.


Ans.A palindrome is a string that reads the same backward as forward (e.g., "madam", "racecar"). To
check if a string is a palindrome in JavaScript, we can write a function that compares the original string
with its reversed version.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Palindrome Checker</title>
<script>
// Function to check if a string is a palindrome
function isPalindrome(str) {
// Remove non-alphanumeric characters and convert to lowercase
let cleanedStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');

// Reverse the cleaned string


let reversedStr = cleanedStr.split('').reverse().join('');

// Compare cleaned and reversed strings


return cleanedStr === reversedStr;
}

// Function to check input and display result


function checkPalindrome() {
let inputStr = document.getElementById("inputString").value;

// Check if the string is a palindrome


if (isPalindrome(inputStr)) {
alert("'" + inputStr + "' is a palindrome.");
} else {
alert("'" + inputStr + "' is not a palindrome.");
}
}
</script>
</head>
<body>
<h1>Palindrome Checker</h1>
<p>Enter a string to check if it's a palindrome:</p>

<input type="text" id="inputString" placeholder="Enter a string">


<button onclick="checkPalindrome()">Check</button>
</body>
</html>

(b) Develop javascript to convert the given character to unicode and vice-versa.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Character and Unicode Converter</title>
<script>
// Function to convert character to Unicode
function charToUnicode() {
const charInput = document.getElementById("charInput").value;
if (charInput.length === 0) {
alert("Please enter a character.");
return;
}
const unicodeValue = charInput.charCodeAt(0); // Get Unicode value of the first character
document.getElementById("unicodeOutput").innerText = "Unicode: " + unicodeValue;
}

// Function to convert Unicode to character


function unicodeToChar() {
const unicodeInput = document.getElementById("unicodeInput").value;
if (unicodeInput.length === 0 || isNaN(unicodeInput)) {
alert("Please enter a valid Unicode value.");
return;
}
const charValue = String.fromCharCode(parseInt(unicodeInput)); // Convert Unicode to character
document.getElementById("charOutput").innerText = "Character: " + charValue;
}
</script>
</head>
<body>

<h2>Character and Unicode Converter</h2>


<div>
<h3>Convert Character to Unicode</h3>
<label for="charInput">Enter Character:</label><br>
<input type="text" id="charInput" maxlength="1" required><br>
<button onclick="charToUnicode()">Convert to Unicode</button>
<p id="unicodeOutput"></p>
</div>

<div>
<h3>Convert Unicode to Character</h3>
<label for="unicodeInput">Enter Unicode:</label><br>
<input type="text" id="unicodeInput" required><br>
<button onclick="unicodeToChar()">Convert to Character</button>
<p id="charOutput"></p>
</div>

</body>
</html>

(c) Write a javascript program to create a slide show with the group of six images, also simulate the
next and previous transition between slides in your javascript.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Slideshow</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 20px;
}
#slideshow {
width: 600px;
height: 400px;
margin: auto;
overflow: hidden;
position: relative;
}
#slideshow img {
width: 100%;
height: auto;
display: none; /* Initially hide all images */
}
#slideshow img.active {
display: block; /* Show active image */
}
.button {
padding: 10px 15px;
margin: 5px;
cursor: pointer;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
}
.button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>

<h1>Image Slideshow</h1>
<div id="slideshow">
<img src="https://via.placeholder.com/600x400.png?text=Image+1" class="active">
<img src="https://via.placeholder.com/600x400.png?text=Image+2">
<img src="https://via.placeholder.com/600x400.png?text=Image+3">
<img src="https://via.placeholder.com/600x400.png?text=Image+4">
<img src="https://via.placeholder.com/600x400.png?text=Image+5">
<img src="https://via.placeholder.com/600x400.png?text=Image+6">
</div>
<br>
<button class="button" onclick="prevSlide()">Previous</button>
<button class="button" onclick="nextSlide()">Next</button>

<script>
let currentSlide = 0; // Keep track of the current slide
const slides = document.querySelectorAll('#slideshow img'); // Select all images in the slideshow

function showSlide(index) {
// Hide all slides
slides.forEach((slide) => {
slide.classList.remove('active');
});
// Show the current slide
slides[index].classList.add('active');
}

function nextSlide() {
currentSlide = (currentSlide + 1) % slides.length; // Move to the next slide
showSlide(currentSlide);
}

function prevSlide() {
currentSlide = (currentSlide - 1 + slides.length) % slides.length; // Move to the previous slide
showSlide(currentSlide);
}
</script>

</body>
</html>

6.Attempt any TWO of the following : 12

(a) Write a javascript to open a new window and the new window is having two frames. One frame
containing buthon as “click here !”, and after clicking this button an image should open in the
second frame of that child window.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Main Window</title>
<script>
function openNewWindow() {
// Open a new window
const newWindow = window.open("", "newWindow", "width=600,height=400");

// Write HTML content to the new window


newWindow.document.write(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Child Window</title>
<style>
body { margin: 0; }
iframe { border: none; width: 100%; height: 100%; }
</style>
</head>
<body>
<frameset cols="50%,50%">
<frame name="buttonFrame">
<frame name="imageFrame">
</frameset>
</body>
</html>
`);

// Load the button in the first frame


newWindow.frames["buttonFrame"].document.write(`
<html>
<body>
<button onclick="window.parent.frames['imageFrame'].document.body.innerHTML =
'<img src=\'https://via.placeholder.com/400\' alt=\'Image\' />';">
Click Here!
</button>
</body>
</html>
`);

// Load a placeholder content in the second frame


newWindow.frames["imageFrame"].document.write(`
<html>
<body>
<h3>Click the button to see the image!</h3>
</body>
</html>
`);
}
</script>
</head>
<body>

<h2>Main Window</h2>
<button onclick="openNewWindow()">Open New Window</button>

</body>
</html>

(b) Write a javascript to create option list containing list of images and then display images in new
window as per selection.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Selector</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
select {
padding: 10px;
font-size: 16px;
}
button {
padding: 10px 15px;
margin: 10px;
cursor: pointer;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
}
button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>

<h1>Select an Image</h1>
<select id="imageSelector">
<option value="">Select an image</option>
<option value="https://via.placeholder.com/600x400.png?text=Image+1">Image 1</option>
<option value="https://via.placeholder.com/600x400.png?text=Image+2">Image 2</option>
<option value="https://via.placeholder.com/600x400.png?text=Image+3">Image 3</option>
<option value="https://via.placeholder.com/600x400.png?text=Image+4">Image 4</option>
<option value="https://via.placeholder.com/600x400.png?text=Image+5">Image 5</option>
<option value="https://via.placeholder.com/600x400.png?text=Image+6">Image 6</option>
</select>
<button onclick="displayImage()">Display Image</button>

<script>
function displayImage() {
const selector = document.getElementById("imageSelector");
const selectedImageUrl = selector.value; // Get the selected image URL

if (selectedImageUrl) {
// Open the selected image in a new window
window.open(selectedImageUrl, '_blank');
} else {
alert("Please select an image to display.");
}
}
</script>

</body>
</html>

(c) Write a javascript function to generate Fibonacci series till user defined limit.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fibonacci Series Generator</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
button {
padding: 10px 15px;
cursor: pointer;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
}
button:hover {
background-color: #0056b3;
}
.result {
margin-top: 20px;
font-size: 16px;
}
</style>
</head>
<body>

<h1>Fibonacci Series Generator</h1>


<button onclick="generateFibonacci()">Generate Fibonacci Series</button>
<div class="result" id="result"></div>

<script>
function generateFibonacci() {
const limit = parseInt(prompt("Enter the limit for Fibonacci series:"), 10); // Get user-defined limit
const resultDiv = document.getElementById("result");

if (isNaN(limit) || limit <= 0) {


resultDiv.innerHTML = "Please enter a valid positive number.";
return;
}

let fibonacciSeries = [];


let a = 0, b = 1;

while (a <= limit) {


fibonacciSeries.push(a); // Add the current Fibonacci number to the series
let nextNumber = a + b; // Calculate the next Fibonacci number
a = b; // Update a to the next number in the series
b = nextNumber; // Update b to the next number in the series
}

resultDiv.innerHTML = "Fibonacci series up to " + limit + ": " + fibonacciSeries.join(", ");


}
</script>

</body>
</html>

You might also like