You are on page 1of 46

CSS

Important Question &


Answers
Prepared By : Mrs.S.N.Kumbhar
Unit I: Basics of JavaScript Programming
1. Enlist features of JavaScript.
Ans : Features of JavaScript
 JavaScript is a lightweight scripting language made for client-side execution on the browser.
 Interpreter Based.
 Event Handling.
 Light Weight.
 Case Sensitive.
 Control Statements.
 Objects as first-class citizens.
2. Define terms (i)Method, (ii) Property, (iii) Event, (iv) Object Name
Ans : i) Method :
 JavaScript methods are actions that can be performed on objects.
 A JavaScript method is a property containing a function definition.
syntax: objectName.methodName()
e.g. name = person.fullName();
 fullName() as a method of the person object, and fullName as a property.
 The fullName property will execute (as a function) when it is invoked with ().
ii) Property :
 Properties are the values associated with a JavaScript object.
 Properties can usually be changed, added, and deleted, but some are read only.
syntax: objectName.property
e.g. person.age
iii) Event :
 HTML events are "things" that happen to HTML elements.
 When JavaScript is used in HTML pages, JavaScript can "react" on these events.
 Here are some examples of HTML events:
o An HTML web page has finished loading
o An HTML input field was changed
o An HTML button was clicked

iv) Object Name :


 A JavaScript object is a collection of named values.
 It is a common practice to declare objects with the const keyword.
Syntax : name : value

3. Explain JavaScript Variables with an example


Ans : Variables are containers for storing data (storing data values).
i) x, y, and z, are variables, declared with the var keyword-
var x = 5; var y = 6; var z = x + y;

ii) x, y, and z, are variables, declared with the let keyword –


let x = 5; let y = 6; let z = x + y;

iii) x, y, and z, are undeclared variables –


x = 5; y = 6; z = x + y;

4. Explain JavaScript Operators and expressions.


Ans : i) Expressions : An expression is any valid set of literals, variables, operators, and expressions that evaluates
to a single value. The value may be a number, a string, or a logical value.
There are two types of expressions: those that assign a value to a variable, and those that simply have a
value.
ii) Operators : There are different types of JavaScript operators:
 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
a) Arithmetic Operators :

Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement

b) Assignment Operators
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y

c) Comparison Operators

Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator

d) Logical Operators

Operator Description
&& logical and
|| logical or
! logical not
5. Explain function definition.
Ans :
 JavaScript functions are defined with the function keyword.
 You can use a function declaration or a function expression.
 Syntax:
function functionName(parameters)
{
// code to be executed
}
 E.g. : function myFunction(a, b)
{
return a * b;
}

6. What is conditioning statement? Explain if…else and if…else if statement.


Ans :
 Conditional statements are used to decide the flow of execution based on different conditions.
 If a condition is true, you can perform one action and if the condition is false, you can perform another
action.
 In JavaScript we have the following conditional statements:
 Use if to specify a block of code to be executed, if a specified condition is true
 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

i) If….Else statement - If….Else statement if you have to check two conditions and execute a
different set of codes.
e.g. : if (condition)
{
lines of code to be executed if the condition is true
}
else
{
lines of code to be executed if the condition is false
}
ii) if…else if statement - If….Else If….Else statement if you want to check more than two conditions.
e.g. : if (condition1)
{
lines of code to be executed if condition1 is true
}
else if(condition2)
{
lines of code to be executed if condition2 is true
}
else
{
lines of code to be executed if condition1 is false and condition2 is false
}

7. Explain Switch Case statement in JavaScript.


Ans :
 The switch statement is used to perform different actions based on different conditions.
This is how it works:
 The switch expression is evaluated once.
 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 If there is no match, the default code block is executed.
Syntax
switch(expression)
{
case x: // code block
break;
case y: // code block
break;
default:
// code block
}

8. Explain the concept of getter and setters in JavaScript with an example.


Ans : In JavaScript, accessor properties are methods that get or set the value of an object. For that, we use these two
keywords:
 get - to define a getter method to get the property value
 set - to define a setter method to set the property value
 Example :
1. Getter :
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
language: "en",
get lang() {
return this.language;
}
};
// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;

2. Setter :
const person = {
firstName: "John",
lastName: "Doe",
language: "",
set lang(lang) {
this.language = lang;
}
};
// Set an object property using a setter:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;
9. Write a JavaScript program to implement arithmetic operators.
Ans : <html>
<body>
<h1>JavaScript Arithmetic</h1>
<h2>Operator Precedence</h2>
<p>Multiplication has precedence over addition.</p>
<p>But parenthesis has precedence over multiplication.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = (100 + 50) * 3;
</script> </body> </html>

10. Write a JavaScript program to demonstrate if…else if statement.


Ans : <html>
<body>
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<p id="demo"></p>
<script>
const hour = new Date().getHours();
let greeting;
if (hour < 18)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script> </body> </html>
11. Write a JavaScript program to demonstrate Switch case statement.
Ans : <html>
<body>
<h2>JavaScript switch</h2>
<p id="demo"></p>
<script>
let day;
switch (new Date().getDay())
{
case 0: day = "Sunday"; break;
case 1: day = "Monday"; break;
case 2: day = "Tuesday"; break;
case 3: day = "Wednesday"; break;
case 4: day = "Thursday"; break;
case 5: day = "Friday"; break;
case 6: day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script> </body> </html>
Unit II : Array, Function and String
1. What is an array? How to create array in JavaScript.
Ans :
 An array is a special variable, which can hold more than one value.
 You can access the values by referring to an index number.
 Array indexes start with 0.
 [0] is the first element. [1] is the second element.
Syntax : const array_name = [item1, item2, ...];
e.g. : const cars = ["Saab", "Volvo", "BMW"];
2. Explain concept of object as associative array in JavaScript with an example.
Ans :
 Arrays with named indexes are called associative arrays (or hashes).
 JavaScript does not support arrays with named indexes.
 In JavaScript, arrays always use numbered indexes.
e.g. : const person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
person.length; // Will return 3
person[0]; // Will return "John"

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


Ans :
i) concat() :
 The concat() method concatenates (joins) two or more arrays.
 The concat() method returns a new array, containing the joined arrays.
 The concat() method does not change the existing arrays.
Syntax : array1.concat(array2, array3, ..., arrayX)

e.g. const arr1 = ["Cecilie", "Lone"];


const arr2 = [1, 2, 3];
const arr3 = arr1.concat(arr2);

ii) join() :
 The join() method returns an array as a string.
 The join() method does not change the original array.
 Any separator can be specified. The default is comma (,).
Syntax : array.join(separator)

e.g. const fruits = ["Banana", "Orange", "Apple", "Mango"];


let text = fruits.join(" and ");

3. What is (i) shift(), (ii) unshift(), (iii) Pop() and (iv) Push()
Ans :
(i). shift() :
 The shift() method removes the first item of an array.
 The shift() method changes the original array.
 The shift() method returns the shifted element.
Syntax : array.shift()
e.g. : <script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
document.getElementById("demo").innerHTML = fruits;
</script>
O/P : Orange,Apple,Mango

(ii) unshift() :
 The unshift() method adds new elements to the beginning of an array.
 The unshift() method overwrites the original array.
Syntax : array.unshift(item1, item2, ..., itemX)
e.g. : <script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon", "Pineapple");

document.getElementById("demo").innerHTML = fruits;
</script>
O/P : Lemon,Pineapple,Banana,Orange,Apple,Mango

(iii) pop() :
 The pop() method removes (pops) the last element of an array.
 The pop() method changes the original array.
 The pop() method returns the removed element.
Syntax : array.pop()

e.g. : <script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let removed = fruits.pop();
document.getElementById("demo").innerHTML = removed;
</script>
O/P : Mango

(iv) Push() :
 The push() method adds new items to the end of an array.
 The push() method changes the length of the array.
 The push() method returns the new length.
Syntax : array.push(item1, item2, ..., itemX)

e.g. : <script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi", "Lemon");
document.getElementById("demo").innerHTML = fruits;
</script>
O/P : Banana,Orange,Apple,Mango,Kiwi,Lemon

4. Explain the use of split() with an example.


Ans :
split() :
 The split() method splits a string into an array of substrings.
 The split() method returns the new array.
 The split() method does not change the original string.
Syntax : string.split(separator, limit)
e.g. : <html>
<body>
<h2>The split() Method</h2>
<p id="demo"></p>
<script>
let text = "How are you doing today?";
const myArray = text.split(" ", 3);
document.getElementById("demo").innerHTML = myArray;
</script>
</body>
</html>
O/P : The split() Method
How,are,you

5. Define function with an example.


Ans : Function :
 A JavaScript function is a block of code designed to perform a particular task.
 A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
 Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
 The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
 The code to be executed, by the function, is placed inside curly brackets: {}
Syntax : function name(parameter1, parameter2, parameter3)
{
// code to be executed
}
e.g. : <html>
<body>
<h2>JavaScript Functions</h2>
<p id="demo"></p>
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b)
{
return a * b;
}
</script>
</body>
</html>
O/P : 12

6. What is the use of return statement?


Ans : The return statement stops the execution of a function and returns a value.
Syntax : return value;
e.g. : <html>
<body>
<h1>JavaScript Statements</h1>
<h2>The return Statement</h2>
<p id="demo"></p>
<script>
function myFunction()
{
return Math.PI;
}
document.getElementById("demo").innerHTML = myFunction();
// Call a function that returns the value of PI
</script>
</body>
</html>
7. Explain scope of variables declared in function with example.
Ans : Scope determines the accessibility (visibility) of variables.JavaScript has 2 types of scope:
 Local scope
 Global scope
I. Local Scope :
a. They can only be accessed from within the function.
b. Since local variables are only recognized inside their functions, variables with the same name can be
used in different functions.
c. Local variables are created when a function starts, and deleted when the function is completed.
e.g .:<html>
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
myFunction();
function myFunction()
{
let carName = "Volvo"; // Local Scope
document.getElementById("demo1").innerHTML = carName;
}
document.getElementById("demo2").innerHTML = carName;
</script>
</body>
</html>
O/P: Volvo // This value of Local variable scope

II. Global Scope :


a. Variables declared Globally (outside any function) have Global Scope.
b. Global variables can be accessed from anywhere in a JavaScript program.
c. Variables declared with var, let and const are quite similar when declared outside a block.
E.g : <html>
<body>
<p id="demo"></p>
<script>
let carName = "BMW"; // Global Scope
myFunction();
function myFunction()
{
document.getElementById("demo").innerHTML carName;
}
</script>
</body>
</html>
O/P : BMW
8. Write Java script to call function from HTML.
Ans :
 JavaScript is mainly used for actions on user events like onClick(), onMouseOver() etc.
 But what if you need to call a JavaScript function without any user events then it would be to use the
onLoad() of the <body> tag.
e.g. : <html>
<h1> Function called from HTML Example</h1>
<body onLoad="open()"> //Function calling
<script type="text/javascript">
function open()
{
alert("Function called from HTML-Open");
}
</script>
</body>
</html>
9. Explain charCodeAt(), fromCharCode() methods in JavaScript.
Ans :
1. charCodeAt() :
 The charCodeAt() method returns the Unicode of the character at a specified index (position)
in a string.
 The index of the first character is 0, the second is 1, ....
Syntax : string.charCodeAt(index)

e.g.: <script>
let text = "HELLO WORLD";
let code = text.charCodeAt(0);
document.getElementById("demo").innerHTML = code;
</script>

 The index of the last character is string length – 1 get the Unicode of the last character
e.g.: <script>
let text = "HELLO WORLD";
let code = text.charCodeAt(text.length-1);
document.getElementById("demo").innerHTML = code;
</script>

2. fromCharCode() :
 The String.fromCharCode() method converts Unicode values to characters.
 The String.fromCharCode() is a static method of the String object.
Syntax : String.fromCharCode(n1, n2, ..., nX)

e.g.: <script>
let text = String.fromCharCode(65);
document.getElementById("demo").innerHTML = text;
</script>
Unit III : Form and Event Handling
1. Explain building blocks of form.
Ans :  There are few differences between a straight HTML form and a JavaScript-enhanced form.
 The main one being that a JavaScript form relies on one or more event handlers, such as onClick or
onSubmit. These invoke a JavaScript action when the user does something in the form, like clicking a button.
 The event handlers, which are placed with the rest of the attributes in the HTML form tags, are invisible to
a browser that doesn’t support JavaScript.
 An HTML document consist of its basic building blocks which are:
o Tags: An HTML tag surrounds the content and apply meaning to it. It is written between < and > brackets.
o Attribute: An attribute in HTML provides extra information about the element, and it is applied within the
start tag. An HTML attribute contains two fields: name & value.
o Elements: An HTML element is an individual component of an HTML file. In an HTML file, everything
written within tags are termed as HTML elements.
2. Explain form tag with all its attributes.
Ans : The <form> tag is used to create an HTML form for user input.
Attributes :

Attribute Value Description


accept-charset character_set Specifies the character encodings that are to
be used for the form submission
action URL Specifies where to send the form-data when
a form is submitted
autocomplete on Specifies whether a form should have
off autocomplete on or off
enctype application/x-www-form-urlencoded Specifies how the form-data should be
multipart/form-data encoded when submitting it to the server
text/plain (only for method="post")
method get Specifies the HTTP method to use when
post sending form-data
name text Specifies the name of a form
novalidate novalidate Specifies that the form should not be
validated when submitted
rel external Specifies the relationship between a linked
help resource and the current document
license
next
nofollow
noopener
noreferrer
opener
prev
search
target _blank Specifies where to display the response that
_self is received after submitting the form
_parent
_top
3. Explain Button element with example.
Ans :
 The <button> tag defines a clickable button.
 Inside a <button> element you can put text (and tags like <i>, <b>, <strong>, <br>, <img>, etc.). That is
not possible with a button created with the <input> element!
 e.g. : <html>
<body>
<h1>The button Element</h1>
<button type="button" onclick="alert('Hello world!')">Click Me!</button>
</body>
</html>
4. Explain Text element with example.
Ans : Text fields are data entry fields which takes small amount of data from the user. This is one of the most
widely used controls of a Web Form.
e.g. : <HTML>
<HEAD>
<TITLE>Text field Example</TITLE>
<BODY>
<FORM NAME="myform" >
<p> Enter your text here</p>
<input type="text" name="t1" size="20" maxlength="10">
</FORM> </BODY> </HEAD> </HTML>
5. Explain TextArea element with example.
Ans : TextArea is mainly used when the user has to enter large amount of text. Also one can enter multiline text in
TextArea which is not available in Text.
e.g : <HTML>
<HEAD>
<TITLE>TextArea Example</TITLE>
<BODY>
<FORM NAME="myform" >
<p> Enter your address here</p>
<textarea name="ta1" cols="50" rows="20" wrap="hard">
</textarea>
</FORM>
</BODY>
</HEAD>
</HTML>
6. Explain Checkbox element with example.
Ans: A checkbox can be in one of the two states, either checked or unchecked. From a group of checkbox’s user
can select multiple options.
e.g: <HTML>
<HEAD>
<TITLE>Checkbox Example</TITLE>
<BODY>
<FORM NAME="myform" >
Select Class<br>
<input type="checkbox" name="class" value="CO1I"> First Year
<input type="checkbox" name="class" value="CO3I"> Second Year
<input type="checkbox" name="class" value="CO5I" checked="true"> Third Year
</FORM>
</BODY>
</HEAD> </HTML>
7. Explain Radio button element with example.
Ans : Radio buttons are mainly used when the user has to select only one among a group of options. Radio button
has two states and can toggle between them.
e.g. : <HTML>
<HEAD>
<TITLE>Radio button Example</TITLE>
<BODY>
<FORM NAME="myform" >
Select your choice<br>
<input type="radio" name="class" value="no"> First Year
<input type="radio" name="class" value="no"> Second Year
<input type="radio" name="class" value="no"> Third Year
</FORM>
</BODY> </HEAD> </HTML>
8. Explain Select element with example.
Ans : The <select> element is used to create a drop-down list.The <select> element is most often used in a form, to
collect user input.
e.g. : <html>
<body>
<h1>The select element</h1>
<form>
<label for="cars">Choose a car:</label>
<select name="cars" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</body> </html>
9. Explain various Mouse events with example.
Ans : These event types belongs to the MouseEvent Object:

Event Description
onclick The event occurs when the user clicks on an element
oncontextmenu The event occurs when the user right-clicks on an element to open a context menu
ondblclick The event occurs when the user double-clicks on an element
onmousedown The event occurs when the user presses a mouse button over an element
onmouseenter The event occurs when the pointer is moved onto an element
onmouseleave The event occurs when the pointer is moved out of an element
onmousemove The event occurs when the pointer is moving while it is over an element
onmouseout The event occurs when a user moves the mouse pointer out of an element, or out of one
of its children
onmouseover The event occurs when the pointer is moved onto an element, or onto one of its children
onmouseup The event occurs when a user releases a mouse button over an element
10. Explain various keyboard events with example.
Ans : These event types belongs to the KeyboardEvent Object:
Event Description
onkeydown The event occurs when the user is pressing a key

onkeypress The event occurs when the user presses a key

onkeyup The event occurs when the user releases a key

11. Explain JavaScript intrinsic functions with an example.


Ans : JavaScript provides some special set of built in function known as Intrinsic functions. These are the
functions to achieve actions of submit and reset buttons. Intrinsic functions are defined by JavaScript.
e.g: <html>
<h1>Intrinsic Function</h1>
<body>
<form name="f1" action="" method="get">
<p> College Name <input type="text" name=t1"/><br>
<img src="D:\Desert.jpg" height="40" width="50" onclick="javascript:document.forms.f1.submit()"/>
</form>
</body>
</html>
12. How to disable elements on the form explain with an example.
Ans : The disabled property sets or returns whether a text field is disabled, or not. A disabled element is unusable
and un-clickable. Disabled elements are usually rendered in gray by default in browsers.
e.g. : <html>
<body>
Name: <input type="text" id="myText">
<button onclick="myFunction()">Disable Text field</button>
<script>
function myFunction()
{
document.getElementById("myText").disabled = true;
}
</script>
</body>
</html>
13. Explain readOnly elements in JavaScript with an example.
Ans : The readOnly property sets or returns whether a text field is read-only, or not.
A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it.
e.g. : <html>
<body>
Name: <input type="text" id="myText">
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.getElementById("myText").readOnly = true;
}
</script> </body> </html>
Unit IV Cookies and Browser Data
1. What is a cookie?
Ans : Cookie :
 Cookies are data, stored in small text files, on your computer.
 When a web server has sent a web page to a browser, the connection is shut down, and the server
forgets everything about the user.
 Cookies were invented to solve the problem "how to remember information about the user":
 When a user visits a web page, his/her name can be stored in a cookie.
 Next time the user visits the page, the cookie "remembers" his/her name.
 Cookies are saved in name-value pairs like: username = John Doe

2. What are timers in JavaScript?


Ans :
 The window object allows execution of code at specified time intervals.
 These time intervals are called timing events.
 The setTimeout() and setInterval() are both methods of the HTML DOM Window object.
 The two key methods to use with JavaScript are:

1. setTimeout(function, milliseconds) : Executes a function, after waiting a specified number of


milliseconds.
syntax : window.setTimeout(function, milliseconds);
e.g. : <html>
<body>
<button onclick="setTimeout(myFunction, 3000)">Try it</button>
<script>
function myFunction() {
alert('Hello');
}
</script>
</body>
</html>

2. setInterval(function, milliseconds) : Same as setTimeout(), but repeats the execution of the function
continuously.
Syntax : window.setInterval(function, milliseconds);
e.g. : <html>
<body>
<p id="demo"></p>
<script>
setInterval(myTimer, 1000);
function myTimer() {
const d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</body>
</html>
3. How to create cookie. Explain with an example.
Ans :
 The simplest way to create a cookie is to assign a string value to the document.cookie object.
Syntax :- document.cookie = "key1 = value1;key2 = value2;expires = date";
 Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the
cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.
e.g. : <html>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script type=”text/javascript”>
function setCookie()
{
document.cookie="username=Gramin Poly";
}
function getCookie()
{
if(document.cookie.length!=0)
{
var array=document.cookie.split("=");
alert("Name="+array[0]+" "+"Value="+array[1]);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>
4. How to delete a cookie. Explain with an example.
Ans :
 Deleting a cookie is very simple.
 You don't have to specify a cookie value when you delete a cookie.
 Just set the expires parameter to a past date:
Syntax : document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
e.g. : <html>
<body>
<input type="button" value="Set Cookie" onclick="setCookie()">
<input type="button" value="Get Cookie" onclick="getCookie()">
<input type="button" value="Delete Cookie1" onclick="delCookie1()">
<input type="button" value="Delete Cookie2" onclick="delCookie2()">
<input type="button" value="Delete Cookie3" onclick="delCookie3()">
<script type="text/javascript">
function setCookie()
{
document.cookie="name=Gramin Poly";
}
function getCookie()
{
if(document.cookie.length!=0)
{
alert(document.cookie);
}
else
{
alert("Cookie not avaliable");
}
}
function delCookie1()
{
document.cookie="name=Gramin Poly; expires=Wednesday, August 07,2019 10:00 AM";
alert("Expiry set");
}
function delCookie2()
{
document.cookie="name=Gramin Poly;max-age=0";
alert("Max Age Set to 0");
}
function delCookie3()
{
document.cookie="name=";
alert("Directly deleted cookie");
}
</script>
</body>
</html>
5. How to set expiration date to a cookie. Explain with an example.
Ans :
 Cookies are usually temporary, so you might want to set a precise expiry date.
 Use Expires and set a fixed expiration date.
 The date uses the HTTP date format : <day-name>, <day> <month> <year>
<hour>:<minute>:<second> GMT.
e.g. : const setCookieExpiry = new Date(2020, 8, 17); document.cookie = “name=Gramin; expires =”+
setCookieExpiry.toUTCString() + ';';
 Use toUTCString() for converting Date() method to string.

6. How to open a window? Describe various styles of window.


Ans :
 The Window interface's open() method loads the specified resource into the new or existing
browsing context (window, or tab) with the specified name.
 If the name doesn't exist, then a new browsing context is opened in a new tab or a new window, and
the specified resource is loaded into it.

7. How to change the content of a window? Explain with an example.


Ans : There are following ways of changing the content of window:-
1. Changing the whole content of a window by using document.write().
2. Changing the content of specific element by document.getElementById().
3. Opening a new window in the same window using “_self” attribute of window.open().
e.g.: <html>
<head><p id="para">This is old Window contents</p></head><br>
<input type="button" value="document.write()" onclick="showPopup1()" />
<br>
<input type="button" value="document.getElementById()" onclick="showPopup2()" />
<br>
<input type="button" value="window.open()" onclick="showPopup3()" />
<script type="text/javascript">
function showPopup1()
{
document.write("This is new content by first option");
}
function showPopup2()
{
document.getElementById("para").innerHTML="This is new content by second option";
}
function showPopup3()
{
var oNewWin = window.open("", "_self","height=150,width=300,top=10,left=10,resizable=yes,menubar=yes");
oNewWin.document.open();
oNewWin.document.write("<html><head><title>New Window</title></head>");
oNewWin.document.write("<body>This is a new content by third option!
</body></html>");
}
</script>
</body>
</html>
8. How to scroll a window? Explain with an example.
Ans : The scrollTo() method scrolls the document to specified coordinates.
Syntax : window.scrollTo(x, y) or scrollTo(x, y)
e.g. : <html>
<style>
body {
width: 5000px;
}
</style>
<body>
<h1>The Window Object</h1>
<h2>The scrollTo() Method</h2>
<p>Click to scroll the document.</p>
<button onclick="scrollWin()" style="position:fixed">Scroll to 200 horizontally!</button><br><br>
<script>
function scrollWin() {
window.scrollTo(200, 0);
}
</script>
</body>
</html>
9. How to create a webpage in new window? Explain with an example.
Ans :
 One can create a web page in new window by using document.write() of the window object.
 Here instead of writing any string we have to pass the tags of HTML which we want to use on the
new window.
 The write function automatically converts HTML tags passed within the document.write()
e.g. : <html>
<head>
<title>Document Open/Close Example</title>
</head>
<body>
<P><input type="button" value="Click Me" onclick="showPopup()" />
<script type="text/javascript">
function showPopup()
{
var oNewWin = window.open("", "_blank",
"height=150,width=300,top=10,left=10,resizable=yes,menubar=yes");
oNewWin.document.open();
oNewWin.document.write("<html><head><title>New Window</title></head>");
oNewWin.document.write("<body>This is a new window!</body></html>");
}
</script>
</body>
</html>
10. How JavaScript’s is used in URLs?
Ans :
 JavaScript code can be included on the client side is in a URL following the
javascript: pseudo-protocol specifier.
 This special protocol type specifies that the body of the URL is arbitrary JavaScript code to be
interpreted by the JavaScript interpreter.
 If the JavaScript code in a javascript: URL contains multiple statements, the statements must be
separated from one another by semicolons.
 Such a URL might look like the following:
javascript:var now = new Date(); " <h1>The time is “</h1>”+now
 When the browser "loads" one of these JavaScript URLs, it executes the JavaScript code contained
in the URL and displays the "document" referred to by the URL.
 This "document" is the string value of the last JavaScript statement in the URL. This string will be
formatted and displayed just like any other document loaded into the browser.
11. Write the syntax of and explain use of following methods of JavaScript Timing Event with an example.
a). setTimeout() b). setInterval()
Ans : a) setTimeout() : The setTimeout() method calls a function after a number of milliseconds.
The setTimeout() is executed only once.
Syntax : myTimeout = setTimeout(function, milliseconds);
e.g : <html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
let timeout;
function myFunction()
{
timeout = setTimeout(alertFunc, 3000);
}
function alertFunc()
{
alert("Hello!");
}
</script>
</body>
</html>
Unit V Regular Expression, Rollover and Frames
1. What is regular expression?
Ans : A regular expression :
 A regular expression is a pattern of characters.
 The pattern is used to do pattern-matching "search-and-replace" functions on text.
 In JavaScript, a RegExp Object is a pattern with Properties and Methods.
Syntax : /pattern/modifier(s);
e.g. : <script>
let text = "Visit W3Schools";
let pattern = /w3schools/i;
let result = text.match(pattern);
document.getElementById("demo").innerHTML = result;
</script>
2. Write down procedure of returning a matched character in JavaScript.
Ans :
 The match() method matches a string against a regular expression **
 The match() method returns an array with the matches.
 The match() method returns null if no match is found.
Syntax : string.match(match)

3. Enlist and explain the regular expression and object properties.


Ans :
 A regular expression is an object that describes a pattern of characters.
 The JavaScript RegExp class represents regular expressions, and both String and RegExp define
methods that use regular expressions to perform powerful pattern-matching and search-and-replace
functions on text.
Syntax :- /pattern/modifiers;
 Parameters
pattern − A string that specifies the pattern of the regular expression or another regular expression.
modifiers − An optional string containing any of the "g", "i", and "m" attributes that specify global,
case-insensitive, and multi-line matches, respectively.
 Properties of Regular expression:
Description
Property
Specifies the function that creates an object's prototype.
constructor
Specifies if the "g" modifier is set.
global
ignoreCase Specifies if the "i" modifier is set.
The index at which to start the next match.
lastIndex
Specifies if the "m" modifier is set.
multiline
Returns the text of the pattern.
source

4. What is Frame?
Ans :
 Frames are used to divide the web browser window into multiple sections where each section can be
loaded separately.
 A frameset tag is the collection of frames in the browser window.
e.g. : <html>
<frameset cols = "30%,40%,30%" frameborder="1">
<frame name = "top" src = "D:\Example\arrayByConstructor.html" />
<frame name = "main" src = "D:\Example\checkBox.html" />
<frame name = "bottom" src = "D:\Example\demo1.html" />
</frameset>
</html>
5. What is rollover?
Ans :
 Rollover is a JavaScript technique used by Web developers to produce an effect in which the
appearance of a graphical image changes when the user rolls the mouse pointer over it.
 Rollover also refers to a button on a Web page that allows interactivity between the user and the
Web page.
 Rollover can be accomplished using text, buttons or images, which can be made to appear when the
mouse is rolled over an image.
 The user needs two images/buttons to perform rollover action.
 The keyword that is used to create rollover is the event.
e.g. : <html>
<body>
<img src="D:\Tulips.jpg" boarder="0px" width="300px" height="200px"
onmouseover="this.src='D:\Desert.jpg';" onmouseout="this.src='D:\Penguins.jpg';" />
</body>
</html>
6. What is text rollover?
Ans :
 The keyword that is used to create rollover is the event.
 For example, we want to create a rollover text that appears in a text area.
 The text “What is rollover?” appears when the user place his or her mouse over the text area and the
rollover text changes to “Rollover means a webpage changes when the user moves his or her mouse
over an object on the page” when the user moves his or her mouse away from the text area.
e.g. : <html>
<body>
<textarea rows="2" cols="50" name=rollovertext" onmouseover="this.value='What is text rollover?';"
onmouseout="this.value='Rollover means changes when the user moves the mouse on the
page';"></textarea>
</body>
</html>
7. Explain the language of regular expression.
Ans : When we create a set of word by using the different patterns of the regular expression in JavaScript it is
known as language of regular expression. Following are some of the patterns available:
1. Brackets: Brackets ([]) : have a special meaning when used in the context of regular expressions. They are
used to find a range of characters.
• [...] - Any one character between the brackets.
• [^...] - Any one character not between the brackets.
• [0-9] - It matches any decimal digit from 0 through 9.
• [a-z] It matches any character from lowercase a through lowercase z.
• [A-Z] It matches any character from uppercase A through uppercase Z.
• [a-Z] It matches any character from lowercase a through uppercase Z.
2. Qualifiers : The frequency or position of bracketed character sequences and single characters can be denoted
by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a
character sequence
• p+ : It matches any string containing one or more p's
• p* : It matches any string containing zero or more p's
• p? : It matches any string containing at most one p
• p$ : It matches any string with p at the end of it.
3. Metacharacters : A metacharacter is simply an alphabetical character preceded by a backslash that acts to give
the combination a special meaning.
1. . - a single character
2. \s - a whitespace character (space, tab, newline)
3. \S - non-whitespace character
4. \d - a digit (0-9)
5. \D - a non-digit
6. \w - a word character (a-z, A-Z, 0-9, _)
7. \W - a non-word character
8. [\b] - a literal backspace (special case).
9. [aeiou] - matches a single character in the given set
10. [^aeiou] - matches a single character outside the given set
11. \t - a tab character
12. \n - a newline character
13. \v - a vertical tab
8. How to match punctuations and symbols? Explain with an example.
Ans :
 Regular expression patterns include the use of letters, digits, punctuation marks, etc., plus a set of
special regular expression characters.
 The characters that are given special meaning within a regular expression, are: . * ? + [ ] ( ) { } ^ $ |
\. You will need to backslash these characters whenever you want to use them literally. For example,
if you want to match ".", you'd have to write \..
 All other characters automatically assume their literal meanings.
e.g. : <html>
<input type="text" name="tx1">
<input type="submit" value="check" onclick="check()">
<script type="text/javascript">
function check()
{
var email=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-z])+$/;
if(tx1.value.match(email))
{
alert("valid mail id");
}
else
{
alert("invalid mail id");
}
}
</script>
</html>
9. How to match words? Explain with an example.
Ans : match() is an inbuilt function in JavaScript which is used to search a string for a match against a any regular
expression and if the match will found then this will return the match as an array.
e.g. : <html>
<input type="text" id="tx1"><br>
<input type="button" value="click" onclick="check()">
<script type="text/javascript">
function check()
{ var str=tx1.value;
var chkPtrn=/poly/i;
if(str.match(chkPtrn))
{ alert("String contains the given pattern");
}
else
{ alert("String does not contains the given pattern");
}
} </script> </html>
10. How to create frames also explain the attributes of Frameset and Frame tag.
Ans : To use frames on a page we use tag instead of tag. The tag defines how to divide the window into frames.
 Attributes of Frameset tag:
 Attributes of Frame tag :
11. How to set the border of the frame invisible? Explain with an example.
Ans : Frameborder attribute of frameset tag is used to specify whether the three dimensional border should be
displayed between the frames or not for this use two values 0 and 1, where 0 defines for no border and value 1
signifies for yes there will be border.
e.g. : <html>
<frameset cols = "30%,40%,30%" >
<frame name = "top" frameborder="0"/>
<frame name = "main" frameborder="0"/>
<frame name = "bottom" frameborder="0"/>
</frameset>
</html>
12. How to call a child window? Explain with an example.
Ans :
 We need to interact with other frames with JavaScript function.
 Every frame is parent or child of parent. Every frame has own id and frame name which differentiate
one frame to other frames.
 We denote frame as child or parent. This makes it easy to access other frame from frame to frame.
e.g. : Example:- (Parent Frame)
<html>
<frameset cols="25%,75%">
<frame src="d:\child1.html" name="frame1"/>
<frame src="d:\child2.html" name="frame2"/>
</frameset>
</html>
Example: - (Child Frame1)
<html>
<body>
<input type="button" value="click" onclick="parent.frame2.disp()"/>
</body>
</html>
Example: - (Child Frame2)
<html>
<script type="text/javascript">
function disp()
{
document.write("This function is called from Frame1");
}
</script>
</html>
13. How to change the content and focus of child window? Explain with an example.
Ans : The content and focus of child window can be changed from another child window. This can be done by
changing the source file for the particular by using JavaScript.
e.g. : (Parent Frame)
<html>
<frameset cols="25%,75%">
<frame src="d:\child1.html" name="frame1"/>
<frame src="d:\child2.html" name="frame2"/>
</frameset>
</html>
(Child Frame1)
<html>
<body>
<input type="button" value="click" onclick="disp()"/>
<script type="text/javascript">
function disp()
{ parent.frame2.location.href="d:\\ child3.html";
}
</script> </body> </html>
(Child Frame2)
<html>
<h1>Frame2</h2>
</html>
(Child Frame3)
<html>
<h1>Content & focus changed from child2 to child3</h2>
</html>
14. How to access the elements of child window from another child window? Explain with an example.
Ans : One can change access the elements of one child window from another by getting the ID of the element used.
e.g : (Parent Frame)
<html>
<frameset cols="25%,75%">
<frame src="d:\child1.html" name="frame1"/>
<frame src="d:\child2.html" name="frame2"/>
</frameset> </html>
(Child Frame1)
<html>
<body>
<input type="button" value="click" onclick="disp()"/>
<script type="text/javascript">
function disp()
{
parent.frame2.document.getElementById("p1").innerHTML="Element is accessed by frame 2";
}
</script> </body> </html>
(Child Frame2)
<html>
<h1>Frame2</h2>
<p id="p1"> Frame 2 contents</p>
</html>
15. How to perform multiple actions by using rollover? Explain with example.
Ans : One can perform multiple actions on the rollover event of mouse like displaying image and displaying text
for that image.
e.g. : <html>
<body>
<a href="" onmouseover="disp()"> Tulip</a><br><br>
<img src="" name="im1" width="200" height="200"><br><br>
<p id="p1">Description of Flower</p>
<script type="text/javascript">
function disp()
{
document.im1.src="D:\Tulips.jpg";
document.getElementById("p1").innerHTML="This is Tulip Flower";
}
</script>
</body> </html>
Unit VI Menus Navigation and Web Page Protection
1. What is slide show?
Ans :
 A web slideshow is a sequence of images or text that consists of showing one element of the sequence in a
certain time interval.
 In the slideshow JavaScript code, we create an array MySlides to store the banner images using the
following statement:
MySlides=new Array(‘banner1.jpg’,’banner2.jpg’,’banner3.jpg’,’banner4.jpg’)
2. What is menu in JavaScript? List and explain various types of menus available.
Ans :
 A menu is a set of options presented to the user of a computer application to help them find
information or execute a function.
 Types Of Menus
a. Creating Pull down Menu : Drop down menus in a website are an important element when it comes to
affective navigation of Webpages.
b. Dynamically changing the Menu: The item of the menu can be changed dynamically depending upon action
takes place.
c. Validating Menu selection: Validation refers to check whether the information if filled correctly. In this case
if the user doesn’t select any option then it prompt user to select appropriate option and proceed
d. Chain Select Menu : Chain select menu is a type of dynamic menu in which there is more than one select
menu present.
e. Tab Menu: Tab menu contain one or more tab-head like a button. Each tab contains separate content to
display.
f. Popup Menu : Popup menu is nothing but a hover able dropdown menu. The drop down menu display the
sub menu on mouse over is known as popup menu.
g. Sliding Menu : Sliding menu is not present on the screen. When we want it we should click on the button or
menu icon then it will slide in the screen
h. Highlighted Menu : Sometimes there is a need to highlight a particular menu item. You can highlight a
menu by adding a different background color, text color etc.
i. Context Menu: When the user click right mouse button on the webpage then the context menu is displayed
and the position of menu is depend on the location where the mouse is clicked.
j. Scrollable Menu : The menu in which items can be scrolled to display limited item on screen is called
scrollable menu.
k. Side Bar Menu : In side bar menu, the sub menu of a menu item will be displayed on right side of the menu.
When we click on the menu item, the sub menu of that menu will be displayed on right side of the menu.

3. How to build a static message in status bar? Explain with example.


Ans :
 A status bar is located at the bottom of Internet browser windows and many application windows
and displays the current state of the web page or application being displayed.
 In JavaScript a static message is built with the status property of window object.
e.g. : <html>
<body>
<h3>Static message example</h3> <br><br>
<script type="text/javascript">
window.status="This is status bar example";
</script>
</body>
</html>
4. How to change the message of status bar using rollover? Explain with example.
Ans : We will use onMouseOver and onMouseOut events of a hyper link to display or manage the messages.
e.g. : <html>
<head>
<title>JavaScript Status Bar</title></head>
<body>
<a ref="http://www.google.com" onMouseOver="window.status='HTMLcenter';return true"
onMouseOut="window.status='';return true"> HTML center </a>
</body>
</html>
5. How to load and display the banner advertisement? Explain with example.
Ans :
 The JavaScript starts by declaring an array to store the banner images using the new Array keywords, as
follows:
MyBanners=new Array(‘banner1.jpg’,’banner2.jpg’,’banner3.jpg’,’banner4.jpg’);
 Each element in the array is assigned with an index, starting from 0. In our example, banner1.jpg is assigned
with index 0, banner2.jpg is assigned with index 1, banner3.jpg is assigned with index 2 and banner3.jpg is
assigned with index 3.
e.g : <html>
<head>
<script language="Javascript">
MyBanners=new Array('D:\\Images\\Chrysanthemum.jpg','D:\\Images\\Hydrangeas.jpg');
banner=0;
function ShowBanners()
{
if (document.images)
{
banner++;
if (banner==MyBanners.length)
{
banner=0;
}
document.ChangeBanner.src=MyBanners[banner];
setTimeout("ShowBanners()",1000);
}
}
</script>
<body onload="ShowBanners()">
<center>
<img src="D:\Images\Desert.jpg" width="900" height="120" name="ChangeBanner"/>
</center>
</body>
</html>

6. How to link a banner advertisement with URL? Explain with example.


Ans :
 Creating rotating banner images will provide the visitor to your webpage with some basic information.
 However, if you want the visitor to get more information by clicking on the banner images, you need to
create rotating banner ads that contain URL links.
 The JavaScript is basically the same as the previous one but we need to add another array that comprises the
links, as follows:
MyBannerLinks=new Array('URL1','URL2','URL3/','URL4/')
e.g. : <html>
<head>
<script language="Javascript">
MyBanners=new Array('D:\\Images\\Desert.jpg','D:\\Images\\Hydrangeas.jpg');
MyBannerLinks=new Array('http://www.vbtutor.net/','http://www.excelvbatutor.com/');
banner=0;
function ShowLinks()
{
document.location.href=MyBannerLinks[banner];
}
function ShowBanners()
{
if (document.images)
{
banner++;
if (banner==MyBanners.length)
{
banner=0;
}
document.ChangeBanner.src=MyBanners[banner];
setTimeout("ShowBanners()",1000);
}
}
</script>
<body onload="ShowBanners()">
<center>
<a href="javascript: ShowLinks()">
<img src="D:\Images\Chrysanthemum.jpg" width="900" height="120" name="ChangeBanner"/></a>
</center>
</body>
</html>
7. How to create dynamically changing menu? Explain with example.
Ans :
 The item of the menu can be changed dynamically depending upon action takes place.
 There are two pull-down menus, so on the selection of first menu the other menu item is changed
dynamically
e.g. : <html>
<select id="cl1" name="cl1" onchange="populate(this.id,'cl2')">
<option value="Class">Class</option>
<option value="FY">First</option>
<option value="SY">Second</option>
</select></hr>
<select id="cl2" name="cl2"> </select> </hr>
<script language="javascript">
function populate(f1,f2)
{
var f1=document.getElementById(f1);
var f2= document.getElementById(f2);
f2.innerHTML="";
if(f1.value=="FY")
{
var newOption=document.createElement("option");
newOption.innerHTML="C";
f2.options.add(newOption);
}
if(f1.value=="SY")
{
var newOption=document.createElement("option");
newOption.innerHTML="RDM";
f2.options.add(newOption);
}
}
</script>
</html>
8. How to validate menu selection? Explain with example.
Ans :
 Validation refers to check whether the information if filled correctly.
 In this case if the user doesn’t select any option then it prompt user to select appropriate option and proceed.
e.g. : <html>
<body>
<form>
<select id="mySelect" onchange="myFunction()">
<option value="sel">Select Subject</option>
<option>C</option>
<option>OOP</option>
<option>JavaScript</option>
</select>
</form>
<p id="demo"></p>
<script language="javascript">
function myFunction()
{
var x = document.getElementById("mySelect");
var i = x.selectedIndex;
if (i==0)
{
alert("Please select subject");
}
else
{
alert(x.options[i].text);
}
}
</script>
</body>
</html>
9. How to create chain select menu?
Ans :
 Dependent or chained dropdown list is a special field that relies on a previously selected field so to display a
list of filtered options.
 Chain select menu is a type of dynamic menu in which there is more than one select menu present. The
option selected from first menu decides the options of second menu and option selected from second menu
decides the option of third menu.
 A common use case is on the selection of state/province and cities, where you first pick the state, and then
based on the state, the application displays a list of cities located in the state.
10. How to protect the webpage?
Ans :
1. Keep software up to date : It may seem obvious, but ensuring you keep all software up to date is vital in
keeping your site secure.

2. Watch out for SQL injection : SQL injection attacks are when an attacker uses a web form field or URL
parameter to gain access to or manipulate your database.

3. Protect against XSS attacks : Cross-site scripting (XSS) attacks inject malicious JavaScript into your pages,
which then runs in the browsers of your users, and can change page content, or steal information to send
back to the attacker.

4. Beware of error messages : Be careful with how much information you give away in your error messages.
Provide only minimal errors to your users, to ensure they don't leak secrets present on your server (e.g. API
keys or database passwords).

5. Validate on both sides : Validation should always be done both on the browser and server side.

6. Check your passwords : It is crucial to use strong passwords to your server and website admin area, but
equally also important to insist on good password practices for your users to protect the security of their
accounts.

7. Avoid file uploads : The risk is that any file uploaded, however innocent it may look, could contain a script
that when executed on your server, completely opens up your website.

8. Use HTTPS : HTTPS is a protocol used to provide security over the Internet.

9. Get website security tools : The most effective way of doing this is via the use of some website security
tools, often referred to as penetration testing or pen testing for short.

10. Disable right click: - Source code of the webpage of some websites can be viewed by right clicking and
click on view source option. By disabling the right click one can hide the source code from the other users.
Program
Section
1. Write a JavaScript program to implement arithmetic operators.
Ans : <html>
<body>
<h1>JavaScript Arithmetic</h1>
<p id="demo"></p>
<script>
let a = 3;
let x = (100 + 50) * a;
document.getElementById("demo").innerHTML = x;
</script> </body> </html>
2. Write a JavaScript program to demonstrate if…else if statement.
Ans : <html>
<body>
<h2>JavaScript if .. else</h2>
<p id="demo"></p>
<script>
const time = new Date().getHours();
let greeting;
if (time < 10)
{
greeting = "Good morning";
}
else if (time < 20)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script> </body> </html>
3. Write a JavaScript program to demonstrate Switch case statement.
Ans : <html>
<body>
<h2>JavaScript switch</h2>
<p id="demo"></p>
<script>
let day;
switch (new Date().getDay())
{
case 0: day = "Sunday";
break;
case 1: day = "Monday";
break;
case 2: day = "Tuesday";
break;
case 3: day = "Wednesday";
break;
case 4: day = "Thursday";
break;
case 5: day = "Friday";
break;
case 6: day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script> </body> </html>
4. Write a JavaScript program to demonstrate for loop statement.
Ans: <html>
<body>
<h2>JavaScript For Loop</h2>
<p id="demo"></p>
<script>
let text = "";
for (let i = 0; i < 5; i++)
{
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
5. Write a JavaScript program to demonstrate while loop statement.
Ans : <html>
<body>
<h2>JavaScript While Loop</h2>
<p id="demo"></p>
<script>
let text = "";
let i = 0;
while (i < 10)
{
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
6. Write a JavaScript program to create and initialize array elements.
Ans : <html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
7. Write a JavaScript program to demonstrate shift(), unshift(), push(),pop(), splice().
Ans : a. The unshift() Method
<html>
<body>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon", "Pineapple");
document.getElementById("demo").innerHTML = fruits;
</script> </body> </html>

b. The shift() Method


<html>
<body>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
document.getElementById("demo").innerHTML = fruits;
</script> </body> </html>

c. The pop() Method


<html>
<body>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
document.getElementById("demo").innerHTML = fruits;
</script> </body> </html>

d. The push() Method


<html>
<body>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
document.getElementById("demo").innerHTML = fruits;
</script> </body> </html>

8. Write a JavaScript program to create a function.


Ans : <html>
<body>
<p id="demo"></p>
<script>
function myFunction(p1, p2)
{
return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script> </body> </html>
9. Write a JavaScript program to declare a string.
Ans : <html>
<body>
<p id="demo"></p>
<script>
let carName1 = "Volvo XC60"; // Double quotes
let carName2 = 'Volvo XC60'; // Single quotes
document.getElementById("demo").innerHTML =
carName1 + " " + carName2;
</script> </body> </html>
10. Write a JavaScript program to demonstrate string concatenation using concat().
Ans : <html>
<body>
<p id="demo"></p>
<script>
let text1 = "Hello";
let text2 = "world!";
let result = text1.concat(" ", text2);
document.getElementById("demo").innerHTML = result;
</script> </body> </html>
11. Write a JavaScript program to retrieve character at specified position from string.
Ans : <html>
<body>
<p id="demo"></p>
<script>
let text = "HELLO WORLD";
let letter = text.charAt(1);
document.getElementById("demo").innerHTML = letter;
</script> </body> </html>
12. Write a JavaScript program to implement indexOf().
Ans : <html>
<body>
<p id="demo"></p>
<script>
let text = "Hello world, welcome to the universe.";
let result = text.indexOf("welcome");
document.getElementById("demo").innerHTML = result;
</script> </body> </html>
13. Write a JavaScript program to implement substr().
Ans : <html>
<body>
<p id="demo"></p>
<script>
let text = "Hello world!";
let result = text.substring(1, 4);
document.getElementById("demo").innerHTML = result;
</script> </body> </html>
14. Write a JavaScript program to change all characters to Uppercase.
Ans : <html>
<body>
<p id="demo"></p>
<script>
let text = "Hello World!";
let result = text.toUpperCase();
document.getElementById("demo").innerHTML = result;
</script> </body> </html>

15. Write a JavaScript program to change all characters to Lowercase


Ans : <html>
<body>
<p id="demo"></p>
<script>
let text = "Hello World!";
let result = text.toLowerCase();
document.getElementById("demo").innerHTML = result;
</script> </body> </html>

16. Write a JavaScript program to implement onsubmit event.


Ans : <html>
<body>
<form action="/action_page.php" onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function myFunction()
{
alert("The form was submitted");
}
</script> </body> </html>
17. Write a JavaScript program to implement onreset event.
Ans : <html>
<body>
<form onreset="myFunction()">
Enter name: <input type="text">
<input type="reset">
</form>
<script>
function myFunction()
{
alert("The form was reset");
}
</script> </body> </html>
18. Write a JavaScript program to demonstrate textarea element.
Ans : <html>
<body>
Address:<br> <textarea id="myTextarea">
342 Alvin Road
Ducksburg</textarea>
<button type="button" onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x = document.getElementById("myTextarea").value;
document.getElementById("demo").innerHTML = x;
}
</script> </body> </html>
19. Write a JavaScript program to demonstrate checkbox element.
Ans : <html>
<body>
<label for="myCheck">Checkbox:</label>
<input type="checkbox" id="myCheck" onclick="myFunction()">
<p id="text" style="display:none">Checkbox is CHECKED!</p>
<script>
function myFunction()
{
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (chekBox.checked == true){
text.style.display = "block";
} else {
text.style.di splay = "none";
}
}
</script> </body> </html>

20. Write a JavaScript program to demonstrate radio button element.


Ans : <html>
<body>
<input type="radio" id="myRadio"> Radio Button
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("myRadio");
x.checked = true;
}
</script> </body> </html>
21. Write a JavaScript program to demonstrate select element.
Ans : <html>
<body>
<form>
<select id="mySelect" size="4">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
</form>
<p>Click the button to display the number of options in the drop-down list.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("mySelect").options.length;
document.getElementById("demo").innerHTML = "Found " + x + " options in the list.";
}
</script> </body> </html>
22. Write a JavaScript program to demonstrate onfocus method.
Ans: <html>
<body>
Enter your name: <input type="text" onfocus="myFunction(this)">
<script>
function myFunction(x)
{
x.style.background = "yellow";
}
</script> </body> </html>
23. Write a JavaScript program to access value from element of form.
Ans : <html>
<body>
<form id="myForm" action="/action_page.php">
First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br>
<input type="submit" value="Submit">
</form>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x = document.getElementById("myForm").elements[0].value;
document.getElementById("demo").innerHTML = x;
}
</script> </body> </html>

24. Write a JavaScript program to read, to write, to delete a cookie value.


Ans : <html>
<head>
<script>
function setCookie(cname,cvalue,exdays)
{
const d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
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 checkCookie()
{
let user = getCookie("username");
if (user != "")
{
alert("Welcome again " + user);
}
else
{
user = prompt("Please enter your name:","");
if (user != "" && user != null)
{
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()"></body>
</html>
25. Write a JavaScript program to open a new window.
Ans : <html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
window.open("https://www.google.com");
}
</script>
</body>
</html>
26. Write a JavaScript program to the focus to a window.
Ans : <html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
Function myFunction()
{
const myWindow = window.open("", "", "width=200,height=100");
myWindow.focus();
}
</script> </body> </html>
27. Write a JavaScript program to set position of a window.
Ans : <html>
<body>
<button onclick="myFunction()">Open Window</button>
<p id="demo"></p>
<script>
functio myFunction()
{
const myWin = window.open("", "", "left=700, top=350, width=200, height=100");
let x = myWin.screenX;
let y = myWin.screenY;
document.getElementById("demo").innerHTML =
"myWin.screenX= " + x + "<br>myWin.screenY= " + y;
}
</script> </body> </html>
28. Write a JavaScript program to close a window.
Ans : <html>
<body>
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
<script>
let myWindow;
function openWin()
{
myWindow = window.open("", "", "width=200,height=100");
}
function closeWin()
{
myWindow.close();
}
</script> </body> </html>
29. Write a JavaScript program to match a character in a range of characters.
Ans : <html>
<body>
<p id="demo"></p>
<script>
let text = "The rain in SPAIN stays mainly in the plain";
let result = text.match(/ain/gi);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
30. Write a JavaScript program to replace a text using regular expression.
Ans : <html>
<body>
<p id="demo">Mr Blue has a blue house and a blue car.</p>
<script>
let str = document.getElementById("demo").innerHTML;
let res = str.replace(/blue/g, "red");
document.getElementById("demo").innerHTML = res;
</script> </body> </html>
31. Write a JavaScript program to create a Frame using cols 20%,50%, 30%.
Ans : <html>
<head>
<title>Frame tag</title>
</head>
<frameset cols="20%,50%,30%">
<frame src="frame1.html" >
<frame src="frame2.html">
<frame src="frame3.html">
</frameset>
</html>
32. Write a JavaScript program to create a Frame using rows 20%,50%, 30%.
Ans : <html>
<head>
<title>Frame tag</title>
</head>
<frameset rows="20%,50%,30%">
<frame src="frame1.html" >
<frame src="frame2.html">
<frame src="frame3.html">
</frameset>
</html>
33. Write a JavaScript program to create rollover.
Ans : <html>
<head>
<title>JavaScript Image Rollovers</title></head>
<body>
<a href="link.html" onMouseOver="document.image1.src='onImage.gif'"
onMouseOut="document.image1.src='outImage.gif'">
<img src="outImage.gif" name="image1">
</a>
</body>
</html>
34. Write a JavaScript program to create a slide show.
Ans : <html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {box-sizing: border-box}
body {font-family: Verdana, sans-serif; margin:0}
.mySlides {display: none}
img {vertical-align: middle;}

/* Slideshow container */
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}

/* Next & previous buttons */


.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -22px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
}

/* Position the "next button" to the right */


.next {
right: 0;
border-radius: 3px 0 0 3px;
}

/* On hover, add a black background color with a little bit see-through */


.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
}

/* Caption text */
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}

/* Number text (1/3 etc) */


.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}

/* The dots/bullets/indicators */
.dot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}

.active, .dot:hover {
background-color: #717171;
}

/* Fading animation */
. fade {
animation-name: fade;
animation-duration: 1.5s;
}

@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}

/* On smaller screens, decrease text size */


@media only screen and (max-width: 300px) {
. prev, .next,.text {font-size: 11px}
}
</style>
</head>
<body>
<div class="slideshow-container">
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img src="img_nature_wide.jpg" style="width:100%">
<div class="text">Caption Text</div>
</div>
<div class="mySlides fade">
<div class="numbertext">2 / 3</div>
<img src="img_snow_wide.jpg" style="width:100%">
<div class="text">Caption Two</div>
</div>
<div class="mySlides fade">
<div class="numbertext">3 / 3</div>
<img src="img_mountains_wide.jpg" style="width:100%">
<div class="text">Caption Three</div>
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❮</a>
</div>
<br>
<div style="text-align:center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>
<script>
let slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
let i;
let slides = document.getElementsByClassName("mySlides");
let dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
}
</script> </body> </html>

You might also like