summer 2024 css
summer 2024 css
Model Answer
Subject: Client Side Scripting Language (22519)
1
d) Write a JavaScript program to display the elements of array in ascending and
descending order.
Ans:
<script> function func()
{
let arr = [45,12,32,78] document.write("Original
Array="+arr);
document.write("<br>Sorted Array="+arr.sort());
document.write("<br>Reverse Array="+arr.reverse());
}
func();
</script>
Ans:
Function is a collection of one or more statements written to execute a specific task.
Syntax to define a function:
function function_name([Arguments])
{
Statement block; [return statement;]
}
Example:
function display ( )
{
alert (―WELCOME TO JAVASCRIPT‖);
}
Ans:
onclickevent: This event occurs when a mouse button is clicked on or over a form
element.
Example:<input type=―text‖ onclick=― function ()‖>
ondblclickevent: This event occurs when a mouse button is double clicked on or over
a form element.
Example:<input type=―text‖ ondblclick=― function ()‖>
onmousedownevent: This event executes when a mouse button is clicked while
cursor is over an element.
Example:<input type=―text‖ onmousedown=― function ()‖>
2
onmouseupevent: This event executes when a mouse button is released while the cursor is
over an element.
Example:<input type=―text‖ onmouseup=― function ()‖>
onmouseoverevent: This event executes when mouse cursor moves onto an element.
Example:<input type=―text‖ onmouseover=― function ()‖>
onmousemoveevent: This event executes when mouse cursor is moved while over an
element.
Example:<input type=―text‖ onmousemove=― function ()‖>
onmouseoutevent: This event executes when mouse cursor is moved away from an
element.
Example:<input type=―text‖ onmouseout=― function ()‖>
g) Explain the term JavaScript URL
Ans:
A URL (Uniform Resource Locator) is the address of a unique resource on the internet. It is
one of the key mechanisms used by browsers to retrieve published resources, such as
HTML pages, CSS documents, images, and so on.
Examples of URLs:
<html> <head>
<title>URL Object</title> </head>
<body>
<script>
const url = new URL('https://www.google.com/my/script/#url');
document.write(url.protocol +"<br>");
document.write(url.host +"<br>");
document.write(url.pathname +"<br>");
document.write(url.hash +"<br>");
document.write(url.origin);
</script>
</body>
</html>
Q.2 Attempt any Three of the following:
3
Property: A property is a value that is associated with an object. The properties of an object are
used to define the characteristics of the object. You access the properties of an object with a
simple dot- notation.
For example, A form object in a web page can have properties like width, height, etc.
Method: A method is used to define a function associated with an object to perform a specific
task. Methods are defined the way normal functions are defined, except that they have to be
assigned as the property of an object.
For example, A submit button placed on a form is an object. Clicking on submit button causes the
button to process a method i.e. when a click event occurs an action is performed and method
executes.
b) Explain setter and getter properties in JavaScript with the help of suitable example
Ans: Property getters and setters
1. The accessor properties. They are essentially functions that work on getting and setting a
value.
2. Accessor properties are represented by ―getter‖ and ―setter‖
methods. In an object literal they are denoted by get and set.
get –It is used to define a getter method to get the property value
set –It is used to define a setter method to set / change the property value
let obj =
{
get propName() {
// getter, the code executed on getting obj.propName
},
set propName(value) {
// setter, the code executed on setting obj.propName = value
}
};
3. An object property is a name, a value and a set of attributes. The value may be replaced by
one or two methods, known as setter and a getter.
Example of getter
const student
{
firstname: ‗abc‗,
get getname() {
return this.firstname;
} };
Example of setter
const student
{
firstname: ‗abc‗,
set changename(nm) {
this.firstname=nm;
} };
4
c) Write a JavaScript program to check whether a number is positive, negative or zero
using switch case.
Ans:
<html>
<body>
<script type="text/javascript">
var num=prompt("Enter number"); switch (Math.sign(num))
{
case 1:
alert("The number is Positive"); break;
case -1:
alert("The number is Negative"); break;
default:
alert("The number is Zero");
}
</script>
</body>
</html>
Output: 97
Output: a
5
The content or values of associative arrays is accessed by keys. An associative array is an
array with string keys rather than numeric keys.
For example:
var arrAssociative = { "Company Name": 'Flexiple', "ID":
123
};
var arrNormal = ["Flexiple", 123];
Here, the keys of the associative array are ―Company Name‖ & ―ID‖
whereas in the normal array. The keys or index is 0 & 1.
b) Write a JavaScript function that checks whether a passed string is palindrome or not.
Ans:
function isPalindrome(str) {
str = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase(); return str = = =
str.split('').reverse().join('');
}
console.log(isPalindrome("A man, a plan, a canal, Panama")); // Output: true
console.log(isPalindrome("racecar")); // Output: true console.log(isPalindrome("hello")); // Output:
false
c) Explain how to add and sort elements in array with suitable example.
Ans:
Adding Elements to an Array:
In JavaScript, you can add elements to an array using various methods, such as push(), unshift(),
or direct assignment to a specific index.
Using push():
The push() method adds one or more elements to the end of an array and returns the new length
of the array.
Using unshift():
The unshift() method adds one or more elements to the beginning of an array and returns the new
length of the array.
Using splice():
This method can be used to add new items to an array, and removes elements from an array.
Syntax: arr.splice(start_index,removed_elements,list_of_elemnts_to_be_add ed);
Parameter:
•The first parameter defines the position where new elements should be added (spliced in).
•The second parameter defines how many elements should be
removed.
•The list_of_elemnts_to_be_added parameter define the new
elements to be added(optional).
Using length property:
The length property provides an easy way to append a new element to an array.
6
Example
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits+"<br>");
fruits[fruits.length] = "Kiwi"; document.write(fruits+"<br>");
fruits[fruits.length] = "Chikoo"; document.write(fruits);
</script>
Sorting Elements in an Array:
JavaScript provides the sort() method to sort the elements of an array in place and returns the sorted
array.
Example
let numbers = [5, 2, 8, 1, 4]; numbers.push(7);
console.log("Array before sorting:", numbers); numbers.sort((a, b) => a - b);
console.log("Array after sorting:", numbers);
7
Example:
<html>
<head>
<script>
function goBack() { window.history.back()
}
</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()">
</body>
</html>
Q.4 Attempt any Three of the following:
a) State what is frame? Explain how it can be created with suitable example.
Ans:
A frame refers to an HTML element that allows the display of another HTML document within
the current web page. Frames are implemented using the <frameset>, <frame> and <iframe>
(Inline Frame) element in HTML.
Frames are used to divide browser window into multiple sections where each section is
treated as window that can have independent contents. A frame can load separate HTML
document in each frame in a window.
<frameset> tag : A frameset is defined as a set of frames inserted in an HTML web page. These
frames can be in the form of rows and columns in different size. Frameset tells the browser
how to divide the screen into multiple areas.
<frameset> ... </frameset>
Attributes:
cols=”pixels/percentage” Specify number and size of
columns in a frameset. Default
value is 100% (1 column).
rows=”pixels/percentage” Specify number and size of rows in
a frameset. Default value is 100%
(1 row).
<frame> tag : Frame tag is used to insert web page content in a frame. It is an empty tag.
Attributes
src=”URL” Specify address of a web page to be
displayed in a frame.
name=” string” Specify name of the frame which can
be used as target to open a link.
:
8
Code:
<html>
<frameset cols="25%,75%" >
<frame src="page1.html" name="f1">
<frame src="page2.html" name="f2">
</frameset>
</html>
width: 100%;
height: 300px; /* Set the height as desired */
border: 1px solid #ccc; /* Add a border for clarity */
}
</style>
</head>
<body>
<!-- Create a frame with an embedded document -->
<iframesrc="https://www.example.com"></iframe>
</body>
</html>
b) Explain the steps to create floating menu and chain select menu
Ans: A floating menu is a menu that remains visible as the user scrolls down a web page. It's
often used for navigation or providing quick access to important content. Here's how you can
create one:
HTML Structure: Create the HTML structure for the menu. This typically involves using
<nav> or <div> elements for the menu container, and <ul> and <li> elements for the menu items.
CSS Styling: Use CSS to style the menu and make it float on the page. You can use position:
fixed to fix the menu in place and top, bottom, left, or right properties to position it relative to
the viewport. JavaScript (Optional): You can enhance the functionality of the floating menu with
JavaScript. For example, you can add smooth scrolling to anchor links within the menu, or you
can add animations to make the menu appear or disappear dynamically.
Example:
< html>
<head>
<meta name="viewport" content="width=device-width, initial- scale=1.0">
<title>Floating Menu Example</title>
<style>
/* CSS styles for the floating menu */
.floating-menu {
position: fixed; top: 0;
left: 0;
background-color: #333; padding: 10px;
width: 100%;
z-index: 1000; /* Ensure it's above other content */
}
9
.menu-item {
display: inline-block; margin-right: 10px;
color: #fff;
text-decoration: none;
}
</style>
</head>
<body>
<nav class="floating-menu">
<ul>
<li class="menu-item"><a href="#section1">Section 1</a></li>
<li class="menu-item"><a href="#section2">Section 2</a></li>
<!-- Add more menu items as needed -->
</ul>
</nav>
<section id="section1">
<h2>Section 1</h2>
<p>This is the content of section 1.</p>
</section>
<section id="section2">
<h2>Section 2</h2>
<p>This is the content of section 2.</p>
</section>
</body>
</html>
10
<label for="city">City:</label>
<select id="city" disabled>
<option value="">Select a city</option>
</select>
<script>
// JavaScript code to handle the chained select menu
constcountrySelect = document.getElementById('country');
constcitySelect = document.getElementById('city');
// Data source (for demonstration purposes) constcitiesByCountry = {
'usa': ['New York', 'Los Angeles', 'Chicago'],
'uk': ['London', 'Manchester', 'Birmingham']
};
countrySelect.addEventListener('change', function() { constselectedCountry =
this.value;
if (selectedCountry) { citySelect.innerHTML = '';
const cities = citiesByCountry[selectedCountry]; if (cities) {
citySelect.disabled = false;
citySelect.innerHTML += '<option value="">Select a city</option>'; cities.forEach(city => {
citySelect.innerHTML += `<option
value="${city}">${city}</option>`;
});
} else { citySelect.disabled = true; }
} else { citySelect.disabled = true;
citySelect.innerHTML = '<option value="">Select a city</option>';
} });
</script> </body> </html>
11
d) Write a JavaScript function to check whether a given address is a valid IP address or
not.
Ans:
function isValidIPAddress(address) {
const ipv4Regex = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; const match =
address.match(ipv4Regex);
if (match) {
for (let i = 1; i<= 4; i++) { const part =
parseInt(match[i]);
if (part < 0 || part > 255 || isNaN(part)) { return false; // Invalid part
}
}
return true;
} else {
return false;
}
}
<html>
<head>
<script type="text/javascript"> window.status='Welcome to Home
Page';
</script>
</head>
<body>
<h1>Hello welcome to JavaScript</h1>
</body>
</html>
12
Q. 5. Attempt any two of the following:
a) Write HTML script that displays textboxes for accepting username and password.
Write proper JavaScript such that when the user clicks on submit button
i) All textboxes must get disabled and change the color to ‘RED;
and with respective labels
ii) Prompt the error message if the password is less than six characters
Ans:
<html>
<head>
<script>
function disableTxt()
{
document.getElementById("un").disabled = true;
document.getElementById('un').style.color = "red";
document.getElementById('aaa').style.color = "red";
document.getElementById("pass").disabled = true;
document.getElementById('pass').style.color = "red";
document.getElementById('bbb').style.color = "red";
}
function validateform(){
var username=document.myform.username.value; var
password=document.myform.password.value; if (username==null ||
username==""){ alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long."); return false;
}
}
</script>
</head>
<body>
<form name="myform" method="post" action="" onsubmit="return validateform()" >
<label id = "aaa">Username:</label>
<input type="text" id="un" name="username"/>
<label id = "bbb"> Password:
</label>
<input type="password" id="pass" name="password"/>
<br>
<br>
<button onclick="disableTxt()">Disable Text field</button>
</form>
</body>
</html>
13
b) Write a webpage that displays a form that contains an input for students rollno and names
user is prompted to enter the input student rollno and name and rollno becomes value of the
cookie.
Ans:
<html>
<head><script>
function writeCookie()
{
var d=new Date();
d.setTime(d.getTime()+(1000*60*60*24));
with(document.myform)
{
document.cookie="Roll No=" + student.value + ";expires="
+d.toGMTString();
}}
function readCookie()
{
if(document.cookie=="")
document.write("cookies not found");
else
document.write(document.cookie);
}
</script>
</head>
<body>
<form name="myform" action=""> Enter your name:
<input type="text" name="student"><br> Enter your Roll No:
<input type="roll no" name="student"><br>
<input type="Reset" value="Set C" type="button" onclick="writeCookie()">
<input type="Reset" value="Get C" type="button" onclick="readCookie()">
</form></body>
</html>
c) Write a JavaScript to create rollover effect that involves text and images. When the user
places his or her mouse pointer over a book title, the corresponding book images appears
Ans:
<html>
<head> <title> rollovers</title> </head>
<body>
<table border="1" width="100%">
<tbody>
<tr valign="top">
14
<td width="50%">
<a><img height="500" src="motivation.png" width="900" name="clr"></a></td>
<td><a onmouseover="document.clr.src='blue.png' ">
<b><u>Motivational book</u></b></a>
<br>
<a onmouseover="document.clr.src=education.png' ">
<b><u>Educational book</u></b></a>
<br>
</td>
</tr>
</tbody>
</table>
</body>
</html>
Q. 6 Attempt any two of the following:
a)Explain following form control / elements with example Button, Text, TextArea, Select,
Checkbox, Form.
Ans:
Button is created by using following code:
<form method = ―GET‖ action = ― ‖ <input type = ―button‖ name =
―MyButton‖ value = ―Click‖ onclick= ―msg()‖> <form>
There are several types of button, which are specified by the type
attribute:
1. Button which corresponds to the graphic component.
2. Submit, which is associated to the form and which starts the
loading of the file assigned to the action attribute.
3. Image button in which an image loaded from a file.
A Button object also represents an HTML <button> element which
is specified as follows:
<button name = ―btn‖ value = ―MyButton‖ onclick = ―msg()‖>
Example:
<html> <body>
<h2>Show a Push Button</h2>
<p>The button below activates a JavaScript when it is clicked. </p>
<form>
<input type="button" value="Click me" onclick="msg()">
</form> <script>
function msg(){
alert("Hello world!");
}
</script> </body> </html>
15
Text:
Input ―text‖ is an object to enter a single line of text whose content
will be part of form data.
In html a text is created by following code:
<input type=―text‖ name=―textname‖ id=―textid‖ value=― assign_value‖ />
Example:
<script type="text/javascript"> function changeText()
{
var userInput = document.getElementById('userInput').value;
document.getElementById('vp').innerHTML = userInput;
}
</script>
<input type='text' id='userInput' value='Enter Text Here' />
<p>Welcome <b id='vp'>JavaScript</b></p>
<input type='button' onclick='changeText()' value='Change Text'/>
</script>
TextArea:
The Textarea object represents an HTML <textarea> element.
The <textarea> tag indicates a form field where the user can enter a large amount of text.
You can access a <textarea> element by using getElementById()
Example:
<html>
<body>
<textarea cols="30" rows="5" wrap="hard" readonly="yes" disabled="yes">
As you can see many times word wrapping is often the desired look for your textareas. Since it
makes everything nice and easy to read and preserves line breaks.
</textarea>
</body>
</html>
Checkbox:
<input> elements of type checkbox are rendered by default as boxes that are checked (ticked)
when activated. A checkbox allows you to select single values for submission in a form (or not).
Syntax for creating checkbox is:
<input type="checkbox" id="myCheck" onclick="myFunction()"> A checkbox can have only
two states:
1. Checked
Unchecked
16
Example:
<html> <body>
<div> <br>
<input type="checkbox" name="program" id="it" value="IT">
<label for="it">Information Tech</label><br>
<input type="checkbox" name="program" id="co" value="CO" checked>
<label for="co">Computer Engg</label><br>
<input type="checkbox" name="program" id="ej" value="EJ">
<label for="ej">Electronics</label><br>
<button onclick="validate();">Validate</button>
</div>
<div id="status">
</div>
<script>
function validate() {
var elements = document.getElementsByName("program"); var statusText = " ";
for (var index=0;index <elements.length;index++) {
statusText = statusText +
elements[index].value+"="+elements[index].checked+"<br>";
}
document.getElementById("status").innerHTML = statusText;
}
</script> </body> </html>
Select:
Form SELECT elements (<select>) within your form can be accessed and manipulated in
JavaScript via the corresponding Select object.
To access a SELECT element in JavaScript, use the syntax:
document.myform.selectname //where myform and selectname are names of your form/element.
document.myform.elements[i] //where i is the position of the select element within form
document.getElementById("selectid") //where "selectid" is the ID of the SELECT element on the
page.
Example:
<html> <body>
<select id="programs" size="5">
<option>Computer Engineering</option>
<option>Information Technology</option>
<option>Chemical Engineering</option>
<option>Electronics &TeleComm.</option>
</select>
<p>Click the button to disable the third option (index 2) in the
dropdown list.</p>
<button onclick="myFunction()">Disable Option</button>
<script>
17
function myFunction()
{
var x = document.getElementById("programs").options[2].disabled
= true; document.getElementById("programs").options[2].style.color = "red";
}
</script>
</body>
</html>
Form:
A form is a section of an HTML document that contains elements such as radio buttons, text
boxes and option lists. HTML form elements are also known as controls.
Elements are used as an efficient way for a user to enter information into a form. Typical form
control objects also called ―widgets‖ includes the following:
Text box for entering a line of text.
Push button for selecting an action.
Radio buttons for making one selection among a group of options.
Check boxes for selecting or deselecting a single, independent option.
The <form> element can contain one or more of the following form elements:
· <input> · <textarea> · <button> · <select> · <option> · <fieldset> ·
<label>
<legend>
Syntax:
<form name = ―myform‖ id = ―myform‖ action = ―page.html‖ onSubmit = ―test()‖> -----
objects---- </form>
b) Write a JavaScript for protecting web page by implementing the following steps:
i) Hiding your source code
ii) Disabling the right MouseButton
iii) Hiding JavaScript
Ans:
i) Hiding your source code:
Every developer has to admit that, on occasion, they've peeked at the code of a web page or
two by right-clicking and choosing View Source from the context menu.
In fact, this technique is a very common way for developers to learn new techniques for
writing HTML and Javascript. However, some developers don't appreciate a colleague
snooping around their code and then borrowing their work without permission. This is
particularly true about javascript, which are typically more time-consuming to develop than
using HTML to build a web page.
In reality, you cannot hide your HTML code and JavaScript from prying eyes, because a
clever developer can easily write a program that pretends to be a browser and calls your
web page from your web server, saving the web page to disk, where it can then be opened
using an editor. Furthermore, 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.
18
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 hide 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.
19
Next, you need to define empty functions for each function that you define in the external
JavaScript file.
webpage.html
<html>
<head>
<script src="mycode.js" languages="javascript" type = "text / javascript">
</script>
<body>
<h3> Right Click on screen, Context Menu is disabled</h3>
</body>
</html>
mycode.js
window.onload=function() {
document.addEventListener("contextmenu", function(e) {
e.preventDefault();
}, false);
}
c) Develop a JavaScript to create rotating Banner Ads with URL links.
Ans:
<html>
<head> <title>Link Banner Ads</title>
<script language="Javascript" type="text/javascript"> Banners = new
Array('1.jpg','2.jpg')
BannerLink = new Array('google.com/', '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()"><imgsrc="1.jpg" width="400" height="75"
name="RotateBanner" /></a>
</center> </body> </html>
20