Winter 2019 - CSS 1
Winter 2019 - CSS 1
1) Lightweight
JavaScript does not have too many language constructs.
JavaScript uses dynamic typing, so everything that you declare or assign,
the interpreter tries to figure out, what should be the type of a certain
variable.
2) Object-oriented
3) Interpreted based
4) Handling date and Time
5) Validating user inputs
6) Event Handling
(c) Write Java script to create person object with properties firstname, lastname,
age, eye color, delete eye color property and display remaining properties of
person object.
<html>
<body>
<script>
var person={firstname:"Priti",lastname:"Jadhav",age:35,eyecolor:"brown"};
document.write(person.firstname+" "+person.lastname+" "+person.age+"
"+person.eyecolor+"<br>");
delete person.age; //delete operator
document.write(person.firstname+" "+person.lastname+" "+person.age+"
"+person.eyecolor+"<br>");
</script>
</body>
</html>
Output:
Priti Jadhav 35 brown
Priti Jadhav undefined brown
d) Write a Java script that initializes an array called flowers with the names of 3
flowers. The script then displays array elements.
<html>
<head>
<title> Array</title>
</head>
<body>
<script>
var flowers = new Array(3);
flowers[0] = "Lotus";
flowers[1]="Rose";
flowers[2]="Lily";
document.write(flowers);
</script>
</body></html>
Output:
Lotus,Rose,Lily
e) Write the use of CharAt() and indexof() with syntax and example.
<html>
<head>
<script type = "text/javascript">
functionmyfunction() {
alert("how are you");
}
</script>
</head>
<body>
<p>Click the following button to see the function in action</p>
<input type = "button" onclick = "myfunction()" value = "Display">
</body>
</html>
f) Write a Java script to design a form to accept values for user ID & password.
<html>
<body>
<form action=" ">
<label for="fname">User ID:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="pass">Password:</label>
<input type="pass" id="pass" name="pass">
</form>
</html>
Output:
Property Description
hash It returns the anchor portion of a URL.
port It returns the port number the server uses for a URL.
Method Description
assign() It loads a new document.
reload() It reloads the current document.
(a) Explain getter and setter properties in Java script with suitable example.
example: Getters and setters allow you to get and set properties via methods.
<script>
var person = {
firstName: 'Chirag',
lastName: 'Shetty',
get fullName()
{
return this.firstName + ' ' + this.lastName;
},
set fullName (name)
{
var words = name.split(' ');
this.firstName = words[0];
this.firstName = words[0].toUpperCase();
this.lastName = words[1];
}
}
document.write(person.fullName); //Getters and setters allow you to get and
set properties via methods.
document.write("<br>"+"before using set fullname()"+"<br>");
person.fullName = 'Yash Desai'; //Set a property using set
document.writeln(person.firstName); // Yash
document.write(person.lastName); // Desai
</script>
Output:
Chirag Shetty
before using set fullname()
YASH Desai
(b) Explain prompt () and confirm () method of Java script with syntax and
example.
Confirm()
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
Syntax
window.confirm("sometext");
The window.confirm() method can be written without the window prefix.
Example:
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
Prompt()
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed
after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box
returns null.
Syntax
window.prompt("sometext","defaultText");
The window.prompt() method can be written without the window prefix.
<html>
<body>
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
let text;
let person = prompt("Please enter your name:", "yogita");
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
<html>
<head>
<title>Compute the average marks and grade</title>
</head>
<body>
<script>
var students = [['Summit', 80], ['Kalpesh', 77], ['Amit', 88], ['Tejas', 93],
['Abhishek', 65]];
var Avgmarks = 0;
for (var i=0; i < students.length; i++) {
Avgmarks += students[i][1];
}
var avg = (Avgmarks/students.length);
document.write("Average grade: " + (Avgmarks)/students.length);
document.write("<br>");
if (avg < 60){
document.write("Grade : E");
}
else if (avg < 70) {
document.write("Grade : D");
}
else if (avg < 80) {
document.write("Grade : C");
} else if (avg < 90) {
document.write("Grade : B");
} else if (avg < 100) {
document.write("Grade : A");
}
</script>
</body>
</html>
Output:
Average grade: 80.6
Grade : B
d) Write the use of CharAt() and indexof() with syntax and example.
indexOf() It provides the position of a char value present in the given string.
Syntax: string.indexOf(searchvalue, start)
Example:
<script>
var s1="Vidyalankar Polytechnic, Mumbai";
var n=s1.indexOf("a");
document.write(n);
document.write("<br>"+n1);
</script>
3. Attempt any THREE of the following : 4*3=12M
(a) Differentiate between concat() and join() methods of array object.
concat() join()
The concat() method concatenates (joins) two or The join() method returns an array as a
more arrays. string.
The concat() method returns a new array,
containing the joined arrays.
The concat() method separates each value with a Any separator can be specified. The
comma only. default is comma (,).
Syntax: Syntax:
array1.concat(array2, array3, ..., arrayX) array.join(separator)
Example: Example:
<script> <script>
const arr1 = ["CO", "IF"]; var fruits = ["Banana", "Orange", "Apple",
const arr2 = ["CM", "AI",4]; "Mango"];
const arr = arr1.concat(arr1, arr2); var text = fruits.join();
document.write(arr); document.write(text);
</script> var text1 = fruits.join("$$");
document.write("<br>"+text1);
</script>
(b) Write a JavaScript that will replace following specified value with another
value in string.
String = “I will fail”
Replace “fail” by “pass”
Code:
<script>
var m = "I will fail";
document.write(m+"<br>");
var s = m.replace("fail", "pass");
document.write(s);
</script>
Output:
I will fail
I will pass
(c) Write a Java Script code to display 5 elements of array in sorted order.
<script>
var arr1 =["Red", "red", 200,"Blue",100];
document.write("Before sorting arra1=" + arr1);
document.write("<br>After sorting arra1="+ arr1.sort());
</script>
Output:
Before sorting arra1=Red,red,200,Blue,100
After sorting arra1=100,200,Blue,Red,red
//save as hello.html
<html>
<body>
<script>
document.write("Hello Everyone!!!!");
</script>
</body>
</html>
//save as sample.html
<html>
<body>
<script>
var ob=window.open("hello.html","windowName","top=200,left=100,width=250,height=100,status");
</script>
</body>
</html>
<html>
<body>
<button onclick="myFunction()">Open Windows</button>
<script>
function myFunction()
{
window.open("http://www.vpt.edu.in/");
}
</script>
</body>
</html>
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.
A Regular Expression is a sequence of characters that constructs a search pattern. When
you search for data in a text, you can use this search pattern to describe what you are
looking for.
Syntax:
A regular expression is defined with the RegExp () constructor as:
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /[pattern]/attributes;
Here,
• Pattern – A string that specifies the pattern of the regular expression or another
regular expression.
• Attributes – An optional string containing attributes that specify global, case-
insensitive, and multi-line matches.
Serach():
• The search() method searches a string for a specified value, and returns the position
of the match.
• The search value can be string or a regular expression.
• This method returns -1 if no match is found.
Syntax
string.search(searchvalue)
example:
<html>
<body>
<p id="demo"> Blue has a blue house and a blue car.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = document.getElementById("demo").innerHTML;
var res = str.search(/blue/g);
document.getElementById("demo").innerHTML = res;
document.getElementById("demo").style.color = "red";
}
</script>
</body>
</html>
(b) List ways of protecting your webpage and describe any one of them.
There is nothing secret about your web page. Anyone with a little computer knowledge
can use a few mouse clicks to display your HTML code, including your JavaScript, on the
screen.
<html>
<head>
<script>
window.onload = function()
{
document.addEventListener("contextmenu", function(e)
{
e.preventDefault();
}, false);}
</script>
<body>
<h3>Right click on screen,Context Menu is disabled</h3>
</body>
</html>
The preventDefault() method cancels the event if it is cancelable, meaning that the
default action that belongs to the event will not occur.
2) Hiding JavaScript
You can hide your JavaScript from a visitor by storing it in an external file on your web
server. The external file should have the .js file 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 file,
but you won't see the source code for the JavaScript.
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);
}
<html>
<head>
<title>Conceal Email Address</title>
<script>
function CreateEmailAddress()
{
var x = 'abcxyz*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="send" onclick="CreateEmailAddress()">
</body>
</html>
(c) Create a slideshow with the group of three images, also simulate next and
previous transition between slides in your Java script.
<html>
<title>slideshow</title>
<body>
<h2 class="w3-center">Manual Slideshow</h2>
<div class="w3">
<img class="mySlides" src="1.jpg" style="width:50%">
<img class="mySlides" src="2.jpg" style="width:50%">
<img class="mySlides" src="3.jpg" style="width:50%">
<img class="mySlides" src="4.jpg" style="width:50%">
<script>
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n)
{
showDivs(slideIndex += n);
}
function showDivs(n)
{
var i;
var x = document.getElementsByClassName("mySlides");
if (n > x.length)
{
slideIndex = 1
}
if (n < 1)
{
slideIndex = x.length
}
for (i = 0; i < x.length; i++)
{
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}
</script>
</body>
</html>
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) Write a Java script to modify the status bar using on MouseOver and on
MouseOut with links. When the user moves his mouse over the link, it will display
“MSBTE” in the status bar. When the user moves his mouse away from the link the
status bar will display nothing.
<html>
<head>
<title>JavaScript Status Bar</title></head>
<body>
<a href="https://msbte.org.in/"
onMouseOver="window.status='MSBTE';return true"
onMouseOut="window.status='';return true">
MSBTE
</a>
</body>
</html>
<html>
<body>
<html>
<script type="text/javascript">
function modifyList(x)
{
with(document.forms.myform)
{
if(x ==1)
{
optionList[0].text="Kiwi";
optionList[0].value=1;
optionList[1].text="Pine-Apple ";
optionList[1].value=2;
optionList[2].text="Apple";
optionList[2].value=3;
}
if(x ==2)
{
optionList[0].text="Tomato";
optionList[0].value=1;
optionList[1].text="Onion ";
optionList[1].value=2;
optionList[2].text="Cabbage ";
optionList[2].value=3;
}
}
}
</script>
</head>
<body>
<form name="myform" action=" " method="post">
<select name="optionList" size="3">
<option value=1>Kiwi
<option value=1>Pine-Apple
<option value=1>Apple
</select>
<br>
<input type="radio" name="grp1" value=1 checked="true"
onclick="modifyList(this.value)"> Fruits
<input type="radio" name="grp1" value=2 onclick="modifyList(this.value)">
Vegitables
</form>
</body>
</html>
Output:
b) Describe, how to read cookie value and write a cookie value. Explain with
example.
var x = document.cookie;
You can access the cookie like this which will return all the cookies saved for the current
domain.
document.cookie=x;
Example:
<html>
<head>
<script>
function writeCookie()
{
with(document.myform)
{
document.cookie="Name=" + person.value + ";"
alert("Cookie written");
}
}
function readCookie()
{
var x;
if(document.cookie=="")
x="";
else
x=document.cookie;
document.write(x);
}
</script>
</head>
<body>
<form name="myform" action="">
Enter your name:
<input type="text" name="person"><br>
<input type="Reset" value="Set Cookie" type="button" onclick="writeCookie()">
<input type="Reset" value="Get Cookie" type="button" onclick="readCookie()">
</form>
</body>
</html>
c) Write a Java script that displays textboxes for accepting name & email ID & a
submit button. Write Java script code such that when the user clicks on submit
button
(1) Name Validation
(2) Email ID validation
<html>
<head>
<title>Form Validation</title>
</head>
<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit =
"return(validate());">
Name
<input type = "text" name = "Name" /><br>
EMail
<input type = "text" name = "EMail" /> <br>
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
<script type = "text/javascript">
function validate() {
if( document.myForm.Name.value == "" ) {
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
A checkbox is created by using the input element with the type=”checkbox” attribute-
value pair.
A checkbox in a form has only two states (checked or un-checked). Checkboxes can be
grouped together under a common name.
Following example make use of five checkboxes to provide five options to the user
regarding favorite color. After the selection of favorite colors, all selected color names are
displayed as output.
<html>
<head>
<title>Print value of all checked CheckBoxes on Button click.</title>
<script type="text/javascript">
function printChecked()
{
var items=document.getElementsByName('check_print');
var selectedItems="";
for(var i=0; i<items.length; i++)
{
if(items[i].type=='checkbox' && items[i].checked==true)
selectedItems+=items[i].value+"<br>";
}
document.getElementById("y").innerHTML =selectedItems;
}
</script>
</head>
<body>
<big>Select your favourite accessories: </big><br>
<input type="checkbox" name="check_print" value="red">red<br>
<input type="checkbox" name="check_print" value="Blue">Blue<br>
<input type="checkbox" name="check_print" value="Green">Green<br>
<input type="checkbox" name="check_print" value="Yellow">Yellow<br>
<input type="checkbox" name="check_print" value="Orange">Orange<br>
<p><input type="button" onclick='printChecked()' value="Click me"/></p>
You Selected:
<p id="y"></p>
</body>
</html>
Output:
(b) Write a script for creating following frame structure
FRUITS, FLOWERS and CITIES are links to the webpage fruits.html, flowers.html,
cities.html respectively. When these links are clicked, corresponding data appears
in FRAME 3.
Code:
Step1) create 3 text files names as:
Fruits.txt
Flowers.txt
City.txt
Step 2) //frame.html
<html>
<body>
<h1 align="center">FRAME1</h1>
</body>
</html>
Step3) //frame1.html
<html>
<head>
<title>FRAME 1</title>
</head>
<body><H1>FRAME2</H1>
<a href="fruits.txt" target="c"><UL>FRUITS</UL></a>
<br>
<a href="flowers.txt" target="c"><UL>FLOWERS</UL></a>
<br>
<a href="city.txt" target="c"><UL>CITIES</UL></a>
</body>
</html>
Step 4) //frame3.html
<html>
<body>
<h1>FRAME3</h1>
</body>
</html>
Step5) //frame_target.html
<html>
<head>
<title>Create a Frame</title>
</head>
<frameset rows="30%,*" border="1">
<frame src="frame.html" name="a" />
<frameset cols="50%,*" border="1">
<frame src="frame1.html" name="b" />
<frame src="frame3.html" name="c" />
</frameset>
</frameset>
</html>
Output:
(c) Write a Javascript to create a pull – down menu with three options [Google,
MSBTE, Yahoo] once the user will select one of the options then user will be
redirected to that site.
Code:
<html>
<head>
<title>HTML Form</title>
<script language="javascript" type="text/javascript">
function getPage(choice)
{
page=choice.options[choice.selectedIndex].value;
if(page != "")
{
window.location=page;
}
}
</script>
</head>
<body>
<form name="myform" action="" method="post">
Select Your Favourite Website:
<select name="MenuChoice" onchange="getPage(this)">
<option value="select any option">Select</option>
<option
value="https://www.codecademy.com/catalog/language/javascript/">CodeAcademy</o
ption>
<option value="https://www.msbte.org.in">MSBTE</option>
<option value="https://www.javatpoint.com/javascript-tutorial">JavaTpoint</option>
</form>
</body>
</html>