SlideShare une entreprise Scribd logo
1  sur  69
Web Scripting - Java Script
Rajesh B. Walde
Sr.Lecturer(Comp.App.)
GBPIT, New Delhi
JavaScript Functions
• A function is a block of code designed to perform a particular task.
• It is a group of reusable code which can be called anywhere in your
program.
• This eliminates the need of writing the same code again and again.
• It helps programmers in writing modular codes.
• Functions allow a programmer to divide a big program into a number of
small and manageable functions.
• Functions are of two types
• Standard functions (Built-in functions)
• User defined functions
Function Definition
The most common way to define a function in JavaScript is by using
the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by
curly braces.
Syntax :
function functionname(parameter-list)
{
statements
}
Example:
function sayHello()
{
alert("Hello there");
}
User Defined Function
Calling a Function:
To invoke a function somewhere later in the script, you would simply need to
write the name of that function.
Example:
<html>
<head>
<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
</body>
</html>
Function Parameters :
• Function parameters are the names listed in the function definition.
• Function arguments are the real values received by the function when it is invoked.
Inside the function, the arguments behave as local variables.
Example :
<html>
<head>
<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">
</form>
</body>
</html>
The return Statement :
• A JavaScript function can have an optional return statement.
• This is required if you want to return a value from a function.
• This statement should be the last statement in a function.
Example:
<html>
<head>
<script type="text/javascript">
function rectarea(length, breadth)
{
var area;
area = length * breadth;
return area;
}
function result()
{
document.write ("Area of Rectangle is " + rectarea(10,5) );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="result()" value="Area of Rectangle">
</form>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function sub()
{
if(document.getElementById("t1").value == "")
alert("Please enter your name");
else if(document.getElementById("t2").value == "")
alert("Please enter a password");
else if(document.getElementById("t2").value != document.getElementById("t3").value)
alert("Please enter correct password");
else if(document.getElementById("t4").value == "")
alert("Please enter your address");
else
alert("Form has been submitted");
}
</script>
</head>
<body>
<form>
<p align="left">
User Name : <input type="text" id="t1"><br> <br>
Password : <input type="password" id="t2"><br> <br>
Confirm Password : <input type="password" id="t3"><br> <br>
Address : <textarea rows="2" cols="25" id="t4"></textarea><br> <br>
<input type="button" value="Submit" onclick="sub()">
<input type="reset" value="Clear All">
</p>
</form>
</body>
</html>
• The String object lets you work with a series of characters; it wraps JavaScript's
string primitive data type with a number of helper methods.
Syntax :
var val = new String(string);
String Length
This property returns the number of characters in a string.
Syntax :
string.length
Example :
var str = new String( "This is string" );
document.write("str.length is:" + str.length);
Output:
str.length is:14
The String Object
String Methods :
Method Description Syntax
charAt() Returns the character at the specified
index.
string.charAt(index);
concat() Combines the text of two strings and
returns a new string.
string.concat(string2, string3[, ...,
stringN]);
indexOf() Returns the index within the calling
String object of the first occurrence
of the specified value, or -1 if not
found.
string.indexOf(searchValue[, fromIndex])
lastIndexOf() Returns the index within the calling
String object of the last occurrence of
the specified value, or -1 if not found.
string.lastIndexOf(searchValue[,
fromIndex])
replace() Used to find a match between a
regular expression and a string, and
to replace the matched substring
with a new substring.
string.replace(regexp/substr,
newSubStr/function[, flags]);
search() Executes the search for a match
between a regular expression and a
specified string.
string.search(regexp);
Method Description Syntax
slice() Extracts a section of a string and
returns a new string.
string.slice( beginslice [, endSlice] );
split() Splits a String object into an array of
strings by separating the string into
substrings.
string.slice( beginslice [, endSlice] );
substr() Returns the characters in a string
beginning at the specified location
through the specified number of
characters.
string.substr(start[, length]);
substring() Returns the characters in a string
between two indexes into the string.
string.substring(indexA, [indexB])
toLowerCase() Returns the calling string value
converted to lower case.
string.toLowerCase( )
toString() Returns a string representing the
specified object.
string.toString( )
toUpperCase() Returns the calling string value
converted to uppercase.
string.toUpperCase( )
str.length :
Example :
<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.write("str.length is:" + str.length);
</script>
</body>
</html>
Output :
str.length is:14
<!DOCTYPE html>
<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script type="text/javascript">
function sub()
{
var str = new String(document.getElementById("t1").value );
alert("String length is : " + str.length);
}
</script>
<form>
<p align="left">
Enter Text : <input type="text" id="t1"><br><br>
<input type="button" value="Submit" onclick="sub()">
<input type="reset" value="Clear All">
</p>
</form>
</body>
</html>
str.concat()
Example :
<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
<script type="text/javascript">
var str1 = new String( "This is string one" );
var str2 = new String( "This is string two" );
var str3 = str1.concat( str2 );
document.write"Concatenated String :" + str3);
</script>
</body>
</html>
Output :
Concatenated String :This is string oneThis is string two.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script type="text/javascript">
function sub()
{
var str1 = new String(
document.getElementById("t1").value );
var str2 = new String(
document.getElementById("t2").value );
alert("Concatenated string is : " + str1.concat(str2));
}
</script>
<form>
<p align="left">
Enter Text 1 : <input type="text" id="t1"><br><br>
Enter Text 2 : <input type="text" id="t2"><br><br>
<input type="button" value="Submit" onclick="sub()">
<input type="reset" value="Clear All">
</p>
</body>
</html>
charAt()
Example :
<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.writeln("str.charAt(0) is:" + str.charAt(0));
document.writeln("<br />str.charAt(1) is:" + str.charAt(1));
document.writeln("<br />str.charAt(2) is:" + str.charAt(2));
document.writeln("<br />str.charAt(3) is:" + str.charAt(3));
document.writeln("<br />str.charAt(4) is:" + str.charAt(4));
document.writeln("<br />str.charAt(5) is:" + str.charAt(5));
</script>
</body>
</html>
Output:
str.charAt(0) is:T
str.charAt(1) is:h
str.charAt(2) is:i
str.charAt(3) is:s
str.charAt(4) is:
str.charAt(5) is:i
str.indexOf()
Example :
<html>
<head>
<title>JavaScript String indexOf() Method</title>
</head>
<body>
<script type="text/javascript">
var str1 = new String( "This is string one" );
var index = str1.indexOf( "string" );
document.write("indexOf found String :" + index );
document.write("<br />");
var index = str1.indexOf( "one" );
document.write("indexOf found String :" + index );
</script>
</body>
</html>
Output:
indexOf found String :8
indexOf found String :15
str.lastIndexOf()
Example :
<html>
<head>
<title>JavaScript String lastIndexOf() Method</title>
</head>
<body>
<script type="text/javascript">
var str1 = new String( "This is string one and again string" );
var index = str1.lastIndexOf( "string" );
document.write("lastIndexOf found String :" + index );
document.write("<br />");
var index = str1.lastIndexOf( "one" );
document.write("lastIndexOf found String :" + index );
</script>
</body>
</html>
Output :
lastIndexOf found String :29
lastIndexOf found String :15
str.replace()
Example :
<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script type="text/javascript">
var re = "Apples";
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
document.write(newstr );
</script>
</body>
</html>
Output :
oranges are round, and oranges are juicy.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript String Replace Method</title>
</head>
<body>
<script type="text/javascript">
function sub()
{
var str1 = new String( document.getElementById("t1").value );
var str2 = new String( document.getElementById("t2").value );
var str3 = new String( document.getElementById("t3").value );
alert("Replaced string is : " + str1.replace(str2,str3));
}
</script>
<form>
<p align="left">
Enter Text : <input type="text" id="t1"><br><br>
Replace : <input type="text" id="t2"><br><br>
With : <input type="text" id="t3"><br><br>
<input type="button" value="Submit" onclick="sub()">
<input type="reset" value="Clear All">
</p>
</body>
</html>
str.search()
Example :
<html>
<head>
<title>JavaScript String search() Method</title>
</head>
<body>
<script type="text/javascript">
var re = "Apples";
var str = "Apples are round, and apples are juicy.";
if ( str.search(re) == -1 )
{
document.write("Does not contain Apples" );
}
else
{
document.write("Contains Apples" );
}
</script>
</body>
</html>
Output :
Contains Apples
<!DOCTYPE html>
<html>
<head>
<title>JavaScript string search method</title>
</head>
<body>
<script type="text/javascript">
function sub()
{
var str1 = new String( document.getElementById("t1").value );
var str2 = new String( document.getElementById("t2").value );
var pos = str1.search(str2);
if (pos != -1)
alert("String found at position " + pos);
else
alert("String not found");
}
</script>
<form>
<p align="left">
Enter Text : <input type="text" id="t1"><br><br>
Search : <input type="text" id="t2"><br><br>
<input type="button" value="Submit" onclick="sub()">
<input type="reset" value="Clear All">
</p>
</form>
</body>
</html>
str.split()
Example :
<html>
<head>
<title>JavaScript String split() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and apples are juicy.";
var splitted = str.split(" ", 3);
document.write( splitted );
</script>
</body>
</html>
Output :
Apples,are,round,
str.slice()
Example :
<html>
<head>
<title>JavaScript String slice() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and apples are juicy.";
var sliced = str.slice(3, -2);
document.write( sliced );
</script>
</body>
</html>
Output :
les are round, and apples are juic
str.substr()
Example :
<html>
<head>
<title>JavaScript String substr() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and apples are juicy.";
document.write("(1,2): " + str.substr(1,2));
document.write("<br />(-2,2): " + str.substr(-2,2));
document.write("<br />(1): " + str.substr(1));
document.write("<br />(-20, 2): " + str.substr(-20,2));
document.write("<br />(20, 2): " + str.substr(20,2));
</script>
</body>
</html>
Output :
(1,2): pp
(-2,2): ci
(1): pples are round, and apples are juicy.
(-20, 2): Ap
(20, 2): d
str.substring()
Example :
<html>
<head>
<title>JavaScript String substring() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and apples are juicy.";
document.write("(1,2): " + str.substring(1,2));
document.write("<br />(0,10): " + str.substring(0, 10));
document.write("<br />(5): " + str.substring(5));
</script>
</body>
</html>
Output :
(1,2): p
(0,10): Apples are
(5): s are round, and apples are juicy.
str.toLowerCase()
Example :
<html>
<head>
<title>JavaScript String toLowerCase() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toLowerCase( ));
</script>
</body>
</html>
Output :
apples are round, and apples are juicy.
str.toUpperCase()
Example :
<html>
<head>
<title>JavaScript String toUpperCase() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toUpperCase( ));
</script>
</body>
</html>
Output :
APPLES ARE ROUND, AND APPLES ARE JUICY.
str.toString()
Example :
<html>
<head>
<title>JavaScript String toString() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toString( ));
</script>
</body>
</html>
Output :
Apples are round, and Apples are Juicy.
• The math object provides you properties and methods for mathematical
constants and functions.
• All the properties and methods of Math are static and can be called by
using Math as an object without creating it.
Syntax :
The syntax to call the properties and methods of Math are as follows:
var pi_val = Math.PI;
var sine_val = Math.sin(30);
Thus, you refer to the constant pi as Math.PI and you call the sine function
as Math.sin(x), where x is the method's argument.
The Math Object
Property Description
LN2 Natural logarithm of 2, approximately 0.693.
LN10 Natural logarithm of 10, approximately 2.302.
LOG2E Base 2 logarithm of E, approximately 1.442.
LOG10E Base 10 logarithm of E, approximately 0.434.
PI Ratio of the circumference of a circle to its diameter,
approximately 3.14159.
SQRT1_2 Square root of 1/2; equivalently, 1 over the square root of 2,
approximately 0.707.
SQRT2 Square root of 2, approximately 1.414.
Math Properties
Math.SQRT2
Syntax
Math.SQRT2
Example :
<html>
<head>
<title>JavaScript Math SQRT2 Property</title>
</head>
<body>
<script type="text/javascript">
var property_value = Math.SQRT2
document.write("Property Value is : " + property_value);
</script>
</body>
</html>
Output :
Property Value is : 1.4142135623730951
Property Description
abs() Returns the absolute value of a number.
ceil() Returns the smallest integer greater than or equal to a number.
cos() Returns the cosine of a number.
exp() Returns EN, where N is the argument, and E is Euler's constant,
the base of the natural logarithm.
log() Returns the natural logarithm (base E) of a number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is, base exponent.
round() Returns the value of a number rounded to the nearest integer.
sin() Returns the sine of a number.
sqrt() Returns the square root of a number.
tan() Returns the tangent of a number.
Math Methods
Math.max() and Math.min()
Syntax :
Math.max(value1, value2, ... valueN ) ;
Math.min(value1, value2, ... valueN ) ;
Example :
<html>
<head>
<title>JavaScript Math max() Method</title>
</head>
<body>
<script type="text/javascript">
var value1 = Math.max(10, 20, -1, 100);
var value2 = Math.min(10, 20, -1, 100);
document.write(“Maximum Value : " + value1 + ”<br>”);
document.write(“Minimum Value : " + value2 );
</script>
</body>
</html>
Output :
Maximum Value : 100
Minimum Value : -1
Math.pow()
Syntax :
Math.pow(base, exponent ) ;
Where, base − The base number.
exponents − The exponent to which to raise base.
Example :
<html>
<head>
<title>JavaScript Math pow() Method</title>
</head>
<body>
<script type="text/javascript">
var value = Math.pow(7, 2);
document.write("Power Value : " + value );
</script>
</body>
</html>
Output :
Power Value : 49
Math.round()
This method returns the value of a number rounded to the nearest integer.
Syntax :
Math.round(x);
Example :
<html>
<head>
<title>JavaScript Math sqrt() Method</title>
</head>
<body>
<script type="text/javascript">
var value1 = Math.round(10.3);
var value2 = Math.round(10.7);
document.write(“Rounded Value1 : " + value1 + ”<br>”);
document.write(“Rounded Value2 : " + value2);
</script>
</body>
</html>
Output :
Rounded Value1 : 10
Rounded Value2 : 11
Math.ceil
Example:
<html>
<head>
<title>JavaScript Math ceil() Method</title>
</head>
<body>
<script type="text/javascript">
var value = Math.ceil(45.95);
document.write("First Test Value : " + value );
var value = Math.ceil(45.20);
document.write("<br />Second Test Value : " + value );
var value = Math.ceil(-45.95);
document.write("<br />Third Test Value : " + value );
var value = Math.ceil(-45.20);
document.write("<br />Fourth Test Value : " + value );
</script>
</body>
</html>
• The Array object lets you store multiple values in a single variable. It stores a fixed-
size sequential collection of elements of the same type.
• An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
Syntax :
var fruits = new Array( "apple", "orange", "mango" );
var qty = new Array(10,35,15,20,40);
You can create array by simply assigning values as follows −
var fruits = [ "apple", "orange", "mango" ];
Var qty = [10,35,15,20,40];
You will use ordinal numbers to access and to set values inside an array as follows.
• fruits[0] is the first element qty[0] is the first element
• fruits[1] is the second element qty[1] is the second element
• fruits[2] is the third element qty[2] is the third element
The Arrays Object
arr.length property
Javascript array length property returns an unsigned, 32-bit integer that specifies
the number of elements in an array.
Syntax :
array.length
Example :
<html>
<head>
<title>JavaScript Array length Property</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array( 10, 20, 30 );
document.write(“Array length is : " + arr.length);
</script>
</body>
</html>
Output :
Array length is : 3
Method Description
concat() Returns a new array comprised of this array joined with other
array(s) and/or value(s).
join() Joins all elements of an array into a string.
pop() Removes the last element from an array and returns that
element.
push() Adds one or more elements to the end of an array and returns
the new length of the array.
reverse() Reverses the order of the elements of an array -- the first
becomes the last, and the last becomes the first.
sort() Represents the source code of an object
Array Methods
arr.concat()
Returns a new array comprised of this array joined with other array(s) and/or value(s).
Syntax :
array.concat(value1, value2, ..., valueN);
Example :
<html>
<head>
<title>JavaScript Array concat Method</title>
</head>
<body>
<script type="text/javascript">
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
var alphaNumeric = alpha.concat(numeric);
document.write("alphaNumeric : " + alphaNumeric );
</script>
</body>
</html>
Output :
alphaNumeric : a,b,c,1,2,3
arr.join()
Javascript array join() method joins all the elements of an array into a string.
Syntax :
array.join(separator);
Example :
<html>
<head>
<title>JavaScript Array join Method</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array("First","Second","Third");
var str = arr.join(“-");
document.write("<br />str : " + str );
</script>
</body>
</html>
Output :
str : First-Second-Third
arr.push()
Javascript array push() method appends the given element(s) in the last of
the array and returns the length of the new array.
Syntax :
array.push(element1, ..., elementN);
Example :
<html>
<head>
<title>JavaScript Array push Method</title>
</head>
<body>
<script type="text/javascript">
var numbers = new Array(1, 4, 9);
var length = numbers.push(10);
document.write("new numbers is : " + numbers );
</script>
</body>
</html>
Output :
new numbers is : 1,4,9,10
arr.pop()
Javascript array pop() method removes the last element from an array and
returns that element.
Syntax :
array.pop();
Example :
<html>
<head>
<title>JavaScript Array pop Method</title>
</head>
<body>
<script type="text/javascript">
var numbers = [1, 4, 9];
var element = numbers.pop();
document.write("element is : " + element );
</script>
</body>
</html>
Output :
element is : 9
arr.reverse()
Javascript array reverse() method reverses the element of an array. The
first array element becomes the last and the last becomes the first.
Syntax :
array.reverse();
Example :
<html>
<head>
<title>JavaScript Array reverse Method</title>
</head>
<body>
<script type="text/javascript">
var arr = [0, 1, 2, 3];
document.write("The array is : " + arr + "<br>");
document.write("Reversed array is : " + arr.reverse() );
</script>
</body>
</html>
Output :
The array is : 0,1,2,3
Reversed array is : 3,2,1,0
arr.sort()
Javascript array sort() method sorts the elements of an array.
Syntax :
array.sort(compareFunction);
Where, compareFunction − Specifies a function that defines the sort order. If omitted,
the array is sorted lexicographically.
Example :
<html>
<head>
<title>JavaScript Array sort Method</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array(50,10,40,20,30);
document.writeln("<p>Original array : " + arr);
var sorted = arr.sort();
document.writeln("<p>Sorted array : " + sorted );
</script>
</body>
</html>
Output :
Original array : 50,10,40,20,30
Sorted array : 10,20,30,40,50
• JavaScript's interaction with HTML is handled through events that occur
when the user or the browser manipulates a page.
• When the page loads, it is called an event. When the user clicks a button,
that click too is an event.
• Other examples include events like pressing any key, closing a window,
resizing a window, etc.
• Developers can use these events to execute JavaScript coded responses,
which cause buttons to close windows, messages to be displayed to users,
data to be validated, and virtually any other type of response imaginable.
• Some of the most commonly used events are:
• onLoad - occurs when a page/object loads in a browser
• onUnload - occurs just before the user exits a page
• onClick - occurs when an object is clicked
• onSubmit - occurs when you submit a form
• onMouseOver - occurs when you point to an object
• onMouseOut - occurs when you point away from an object
JavaScript Events
onLoad event
• The onload event occurs when an object has been loaded.
• The onload is most often used within the <body> element to execute a
script once a web page has completely loaded all content.
• The onload event can be used to check the visitor's browser type and
browser version, and load the proper version of the web page based on the
information.
Syntax :
In HTML: <element onload="myScript">
In JavaScript: object.onload=function(){myScript};
Example :
<html>
<head>
<script type="text/javascript">
function myFunction()
{
alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h1>onLoad Event!</h1>
</body>
</html>
onUnload event
• The onunload event occurs once a page has unloaded (or the browser
window has been closed).
• onunload occurs when the user navigates away from the page (by clicking
on a link, submitting a form, closing the browser window, etc.).
Syntax :
In HTML: <element onunload="myScript">
In JavaScript: object.onunload=function(){myScript};
Example :
<html>
<head>
<script type="text/javascript">
function myFunction()
{
alert("Page is unloaded");
}
</script>
</head>
<body onUnload="myFunction()">
<h1>onUnload Event!</h1>
</body>
</html>
onClick event
• This is the most frequently used event type which occurs when a user clicks
the left button of his mouse.
• You can put your validation, warning etc., against this event type.
Syntax :
In HTML: <element onClick="myScript">
In JavaScript: object.onClick=function(){myScript};
Example :
<html>
<head>
<script type="text/javascript">
function sayHello() {
alert("Hello World")
}
</script>
</head>
<body>
<h1>onClick Event!</h1>
<p>Click the following button and
see result</p>
<form>
<input type="button"
onclick="sayHello()" value="Say
Hello" />
</form>
</body>
</html>
onSubmit event
• onsubmit is an event that occurs when you try to submit a form.
• You can put your form validation against this event type.
Syntax :
In HTML: <element onSubmit="myScript">
In JavaScript: object.onSubmit=function(){myScript};
Example :
<html>
<head>
<script type="text/javascript">
function myFunction() {
alert("The form was submitted");
}
</script>
</head>
<body>
<h1>onSlick Event!</h1>
<p>When you submit the form, a function
is triggered which alerts some
text.</p>
<form action="demo_form.asp"
onsubmit="myFunction()">
Enter name: <input type="text"
name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
onMouseOver and onMouseOut event
• These two event types will help you create nice effects with images or even
with text as well.
• The onMouseOver event triggers when you bring your mouse over any
element and the onMouseOut triggers when you move your mouse out from
that element.
Syntax :
In HTML: <element onMounseOver="myScript">
In JavaScript: object.onMouseOver=function(){myScript};
In HTML: <element onMounseOut="myScript">
In JavaScript: object.onMouseOut=function(){myScript};
Example :
<html>
<head>
<script>
function bigImg(x) {
x.style.height = "64px";
x.style.width = "64px"; }
function normalImg(x) {
x.style.height = "32px";
x.style.width = "32px"; }
</script>
</head>
<body>
<h1>onMouseOver and onMouseOut Event!</h1>
<img onmouseover="bigImg(this)"
onmouseout="normalImg(this)" border="0"
src="smiley.gif" alt="Smiley“
width="32" height="32">
<p>The function bigImg() is triggered when
the user moves the mouse pointer over the
image.</p>
<p>The function normalImg() is triggered when
the mouse pointer is moved out of the
image.</p>
</body>
</html>
Small project - Image slideshow
<html>
<head>
<script type="text/javascript">
var slideimages = new Array() // create new array to preload images
slideimages[0] = new Image() // create new instance of image object
slideimages[0].src = “image1.gif" // set image src property to image path,
//preloading image in the process
slideimages[1] = new Image()
slideimages[1].src = “image2.gif"
slideimages[2] = new Image()
slideimages[2].src = “image3.gif"
</script>
</head>
<body>
<img src=“image1.gif" id="slide" width="200" height="100" />
<script type="text/javascript">
var step=0 //variable that will increment through the images
function slideit() {
if (!document.images)
return
document.getElementById('slide').src = slideimages[step].src
if (step<2)
step++
else
step=0
setTimeout("slideit()",1000) //call function "slideit()" every 1 seconds
}
slideit()
</script>
</body>
</html>
Thank you
TRAINING PROGRAMME FOR
VOCATIONAL TEACHERS ON
IT APPLICATIONS
(CLASS XII)
DATES: 06/06/2016 TO 15/06/2016
VENUE: SCERT
COORDINATOR: DR. NARESH KAPOOR
STATE COUNCIL OF EDUCATIONAL RESEARCH & TRAINING
VARUN MARG, DEFENCE COLONY,
NEW DELHI

Contenu connexe

Similaire à Javascripting.pptx

JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptxMuqaddarNiazi1
 
Java script
 Java script Java script
Java scriptbosybosy
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)Ajay Khatri
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVAMuskanSony
 
CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29Bilal Ahmed
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functionsmussawir20
 
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdfjavascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdfAlexShon3
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notesGOKULKANNANMMECLECTC
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionKent Huang
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxSirRafiLectures
 
Flex Maniacs 2007
Flex Maniacs 2007Flex Maniacs 2007
Flex Maniacs 2007rtretola
 
Assignment 13assg-13.cppAssignment 13assg-13.cpp   @auth.docx
Assignment 13assg-13.cppAssignment 13assg-13.cpp   @auth.docxAssignment 13assg-13.cppAssignment 13assg-13.cpp   @auth.docx
Assignment 13assg-13.cppAssignment 13assg-13.cpp   @auth.docxbraycarissa250
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Introzhang tao
 

Similaire à Javascripting.pptx (20)

JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptx
 
Java script
 Java script Java script
Java script
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
 
Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
 
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdfjavascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
 
Bw14
Bw14Bw14
Bw14
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptx
 
Flex Maniacs 2007
Flex Maniacs 2007Flex Maniacs 2007
Flex Maniacs 2007
 
Assignment 13assg-13.cppAssignment 13assg-13.cpp   @auth.docx
Assignment 13assg-13.cppAssignment 13assg-13.cpp   @auth.docxAssignment 13assg-13.cppAssignment 13assg-13.cpp   @auth.docx
Assignment 13assg-13.cppAssignment 13assg-13.cpp   @auth.docx
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
 
Templates2
Templates2Templates2
Templates2
 

Dernier

ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 

Dernier (20)

ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 

Javascripting.pptx

  • 1. Web Scripting - Java Script Rajesh B. Walde Sr.Lecturer(Comp.App.) GBPIT, New Delhi
  • 2. JavaScript Functions • A function is a block of code designed to perform a particular task. • It is a group of reusable code which can be called anywhere in your program. • This eliminates the need of writing the same code again and again. • It helps programmers in writing modular codes. • Functions allow a programmer to divide a big program into a number of small and manageable functions. • Functions are of two types • Standard functions (Built-in functions) • User defined functions
  • 3. Function Definition The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. Syntax : function functionname(parameter-list) { statements } Example: function sayHello() { alert("Hello there"); } User Defined Function
  • 4. Calling a Function: To invoke a function somewhere later in the script, you would simply need to write the name of that function. Example: <html> <head> <script type="text/javascript"> function sayHello() { document.write ("Hello there!"); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type="button" onclick="sayHello()" value="Say Hello"> </form> </body> </html>
  • 5.
  • 6. Function Parameters : • Function parameters are the names listed in the function definition. • Function arguments are the real values received by the function when it is invoked. Inside the function, the arguments behave as local variables. Example : <html> <head> <script type="text/javascript"> function sayHello(name, age) { document.write (name + " is " + age + " years old."); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type="button" onclick="sayHello('Zara', 7)" value="Say Hello"> </form> </body> </html>
  • 7.
  • 8. The return Statement : • A JavaScript function can have an optional return statement. • This is required if you want to return a value from a function. • This statement should be the last statement in a function. Example: <html> <head> <script type="text/javascript"> function rectarea(length, breadth) { var area; area = length * breadth; return area; } function result() { document.write ("Area of Rectangle is " + rectarea(10,5) ); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type="button" onclick="result()" value="Area of Rectangle"> </form> </body> </html>
  • 9.
  • 10. <html> <head> <script type="text/javascript"> function sub() { if(document.getElementById("t1").value == "") alert("Please enter your name"); else if(document.getElementById("t2").value == "") alert("Please enter a password"); else if(document.getElementById("t2").value != document.getElementById("t3").value) alert("Please enter correct password"); else if(document.getElementById("t4").value == "") alert("Please enter your address"); else alert("Form has been submitted"); } </script> </head> <body> <form> <p align="left"> User Name : <input type="text" id="t1"><br> <br> Password : <input type="password" id="t2"><br> <br> Confirm Password : <input type="password" id="t3"><br> <br> Address : <textarea rows="2" cols="25" id="t4"></textarea><br> <br> <input type="button" value="Submit" onclick="sub()"> <input type="reset" value="Clear All"> </p> </form> </body> </html>
  • 11.
  • 12. • The String object lets you work with a series of characters; it wraps JavaScript's string primitive data type with a number of helper methods. Syntax : var val = new String(string); String Length This property returns the number of characters in a string. Syntax : string.length Example : var str = new String( "This is string" ); document.write("str.length is:" + str.length); Output: str.length is:14 The String Object
  • 13. String Methods : Method Description Syntax charAt() Returns the character at the specified index. string.charAt(index); concat() Combines the text of two strings and returns a new string. string.concat(string2, string3[, ..., stringN]); indexOf() Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. string.indexOf(searchValue[, fromIndex]) lastIndexOf() Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. string.lastIndexOf(searchValue[, fromIndex]) replace() Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring. string.replace(regexp/substr, newSubStr/function[, flags]); search() Executes the search for a match between a regular expression and a specified string. string.search(regexp);
  • 14. Method Description Syntax slice() Extracts a section of a string and returns a new string. string.slice( beginslice [, endSlice] ); split() Splits a String object into an array of strings by separating the string into substrings. string.slice( beginslice [, endSlice] ); substr() Returns the characters in a string beginning at the specified location through the specified number of characters. string.substr(start[, length]); substring() Returns the characters in a string between two indexes into the string. string.substring(indexA, [indexB]) toLowerCase() Returns the calling string value converted to lower case. string.toLowerCase( ) toString() Returns a string representing the specified object. string.toString( ) toUpperCase() Returns the calling string value converted to uppercase. string.toUpperCase( )
  • 15. str.length : Example : <html> <head> <title>JavaScript String length Property</title> </head> <body> <script type="text/javascript"> var str = new String( "This is string" ); document.write("str.length is:" + str.length); </script> </body> </html> Output : str.length is:14
  • 16. <!DOCTYPE html> <html> <head> <title>JavaScript String length Property</title> </head> <body> <script type="text/javascript"> function sub() { var str = new String(document.getElementById("t1").value ); alert("String length is : " + str.length); } </script> <form> <p align="left"> Enter Text : <input type="text" id="t1"><br><br> <input type="button" value="Submit" onclick="sub()"> <input type="reset" value="Clear All"> </p> </form> </body> </html>
  • 17.
  • 18. str.concat() Example : <html> <head> <title>JavaScript String concat() Method</title> </head> <body> <script type="text/javascript"> var str1 = new String( "This is string one" ); var str2 = new String( "This is string two" ); var str3 = str1.concat( str2 ); document.write"Concatenated String :" + str3); </script> </body> </html> Output : Concatenated String :This is string oneThis is string two.
  • 19. <!DOCTYPE html> <html> <head> <title>JavaScript String length Property</title> </head> <body> <script type="text/javascript"> function sub() { var str1 = new String( document.getElementById("t1").value ); var str2 = new String( document.getElementById("t2").value ); alert("Concatenated string is : " + str1.concat(str2)); } </script> <form> <p align="left"> Enter Text 1 : <input type="text" id="t1"><br><br> Enter Text 2 : <input type="text" id="t2"><br><br> <input type="button" value="Submit" onclick="sub()"> <input type="reset" value="Clear All"> </p> </body> </html>
  • 20.
  • 21. charAt() Example : <html> <head> <title>JavaScript String charAt() Method</title> </head> <body> <script type="text/javascript"> var str = new String( "This is string" ); document.writeln("str.charAt(0) is:" + str.charAt(0)); document.writeln("<br />str.charAt(1) is:" + str.charAt(1)); document.writeln("<br />str.charAt(2) is:" + str.charAt(2)); document.writeln("<br />str.charAt(3) is:" + str.charAt(3)); document.writeln("<br />str.charAt(4) is:" + str.charAt(4)); document.writeln("<br />str.charAt(5) is:" + str.charAt(5)); </script> </body> </html> Output: str.charAt(0) is:T str.charAt(1) is:h str.charAt(2) is:i str.charAt(3) is:s str.charAt(4) is: str.charAt(5) is:i
  • 22. str.indexOf() Example : <html> <head> <title>JavaScript String indexOf() Method</title> </head> <body> <script type="text/javascript"> var str1 = new String( "This is string one" ); var index = str1.indexOf( "string" ); document.write("indexOf found String :" + index ); document.write("<br />"); var index = str1.indexOf( "one" ); document.write("indexOf found String :" + index ); </script> </body> </html> Output: indexOf found String :8 indexOf found String :15
  • 23. str.lastIndexOf() Example : <html> <head> <title>JavaScript String lastIndexOf() Method</title> </head> <body> <script type="text/javascript"> var str1 = new String( "This is string one and again string" ); var index = str1.lastIndexOf( "string" ); document.write("lastIndexOf found String :" + index ); document.write("<br />"); var index = str1.lastIndexOf( "one" ); document.write("lastIndexOf found String :" + index ); </script> </body> </html> Output : lastIndexOf found String :29 lastIndexOf found String :15
  • 24. str.replace() Example : <html> <head> <title>JavaScript String replace() Method</title> </head> <body> <script type="text/javascript"> var re = "Apples"; var str = "Apples are round, and apples are juicy."; var newstr = str.replace(re, "oranges"); document.write(newstr ); </script> </body> </html> Output : oranges are round, and oranges are juicy.
  • 25. <!DOCTYPE html> <html> <head> <title>JavaScript String Replace Method</title> </head> <body> <script type="text/javascript"> function sub() { var str1 = new String( document.getElementById("t1").value ); var str2 = new String( document.getElementById("t2").value ); var str3 = new String( document.getElementById("t3").value ); alert("Replaced string is : " + str1.replace(str2,str3)); } </script> <form> <p align="left"> Enter Text : <input type="text" id="t1"><br><br> Replace : <input type="text" id="t2"><br><br> With : <input type="text" id="t3"><br><br> <input type="button" value="Submit" onclick="sub()"> <input type="reset" value="Clear All"> </p> </body> </html>
  • 26.
  • 27. str.search() Example : <html> <head> <title>JavaScript String search() Method</title> </head> <body> <script type="text/javascript"> var re = "Apples"; var str = "Apples are round, and apples are juicy."; if ( str.search(re) == -1 ) { document.write("Does not contain Apples" ); } else { document.write("Contains Apples" ); } </script> </body> </html> Output : Contains Apples
  • 28. <!DOCTYPE html> <html> <head> <title>JavaScript string search method</title> </head> <body> <script type="text/javascript"> function sub() { var str1 = new String( document.getElementById("t1").value ); var str2 = new String( document.getElementById("t2").value ); var pos = str1.search(str2); if (pos != -1) alert("String found at position " + pos); else alert("String not found"); } </script> <form> <p align="left"> Enter Text : <input type="text" id="t1"><br><br> Search : <input type="text" id="t2"><br><br> <input type="button" value="Submit" onclick="sub()"> <input type="reset" value="Clear All"> </p> </form> </body> </html>
  • 29.
  • 30. str.split() Example : <html> <head> <title>JavaScript String split() Method</title> </head> <body> <script type="text/javascript"> var str = "Apples are round, and apples are juicy."; var splitted = str.split(" ", 3); document.write( splitted ); </script> </body> </html> Output : Apples,are,round,
  • 31. str.slice() Example : <html> <head> <title>JavaScript String slice() Method</title> </head> <body> <script type="text/javascript"> var str = "Apples are round, and apples are juicy."; var sliced = str.slice(3, -2); document.write( sliced ); </script> </body> </html> Output : les are round, and apples are juic
  • 32. str.substr() Example : <html> <head> <title>JavaScript String substr() Method</title> </head> <body> <script type="text/javascript"> var str = "Apples are round, and apples are juicy."; document.write("(1,2): " + str.substr(1,2)); document.write("<br />(-2,2): " + str.substr(-2,2)); document.write("<br />(1): " + str.substr(1)); document.write("<br />(-20, 2): " + str.substr(-20,2)); document.write("<br />(20, 2): " + str.substr(20,2)); </script> </body> </html> Output : (1,2): pp (-2,2): ci (1): pples are round, and apples are juicy. (-20, 2): Ap (20, 2): d
  • 33. str.substring() Example : <html> <head> <title>JavaScript String substring() Method</title> </head> <body> <script type="text/javascript"> var str = "Apples are round, and apples are juicy."; document.write("(1,2): " + str.substring(1,2)); document.write("<br />(0,10): " + str.substring(0, 10)); document.write("<br />(5): " + str.substring(5)); </script> </body> </html> Output : (1,2): p (0,10): Apples are (5): s are round, and apples are juicy.
  • 34. str.toLowerCase() Example : <html> <head> <title>JavaScript String toLowerCase() Method</title> </head> <body> <script type="text/javascript"> var str = "Apples are round, and Apples are Juicy."; document.write(str.toLowerCase( )); </script> </body> </html> Output : apples are round, and apples are juicy.
  • 35. str.toUpperCase() Example : <html> <head> <title>JavaScript String toUpperCase() Method</title> </head> <body> <script type="text/javascript"> var str = "Apples are round, and Apples are Juicy."; document.write(str.toUpperCase( )); </script> </body> </html> Output : APPLES ARE ROUND, AND APPLES ARE JUICY.
  • 36. str.toString() Example : <html> <head> <title>JavaScript String toString() Method</title> </head> <body> <script type="text/javascript"> var str = "Apples are round, and Apples are Juicy."; document.write(str.toString( )); </script> </body> </html> Output : Apples are round, and Apples are Juicy.
  • 37. • The math object provides you properties and methods for mathematical constants and functions. • All the properties and methods of Math are static and can be called by using Math as an object without creating it. Syntax : The syntax to call the properties and methods of Math are as follows: var pi_val = Math.PI; var sine_val = Math.sin(30); Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument. The Math Object
  • 38. Property Description LN2 Natural logarithm of 2, approximately 0.693. LN10 Natural logarithm of 10, approximately 2.302. LOG2E Base 2 logarithm of E, approximately 1.442. LOG10E Base 10 logarithm of E, approximately 0.434. PI Ratio of the circumference of a circle to its diameter, approximately 3.14159. SQRT1_2 Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707. SQRT2 Square root of 2, approximately 1.414. Math Properties
  • 39. Math.SQRT2 Syntax Math.SQRT2 Example : <html> <head> <title>JavaScript Math SQRT2 Property</title> </head> <body> <script type="text/javascript"> var property_value = Math.SQRT2 document.write("Property Value is : " + property_value); </script> </body> </html> Output : Property Value is : 1.4142135623730951
  • 40. Property Description abs() Returns the absolute value of a number. ceil() Returns the smallest integer greater than or equal to a number. cos() Returns the cosine of a number. exp() Returns EN, where N is the argument, and E is Euler's constant, the base of the natural logarithm. log() Returns the natural logarithm (base E) of a number. max() Returns the largest of zero or more numbers. min() Returns the smallest of zero or more numbers. pow() Returns base to the exponent power, that is, base exponent. round() Returns the value of a number rounded to the nearest integer. sin() Returns the sine of a number. sqrt() Returns the square root of a number. tan() Returns the tangent of a number. Math Methods
  • 41. Math.max() and Math.min() Syntax : Math.max(value1, value2, ... valueN ) ; Math.min(value1, value2, ... valueN ) ; Example : <html> <head> <title>JavaScript Math max() Method</title> </head> <body> <script type="text/javascript"> var value1 = Math.max(10, 20, -1, 100); var value2 = Math.min(10, 20, -1, 100); document.write(“Maximum Value : " + value1 + ”<br>”); document.write(“Minimum Value : " + value2 ); </script> </body> </html> Output : Maximum Value : 100 Minimum Value : -1
  • 42. Math.pow() Syntax : Math.pow(base, exponent ) ; Where, base − The base number. exponents − The exponent to which to raise base. Example : <html> <head> <title>JavaScript Math pow() Method</title> </head> <body> <script type="text/javascript"> var value = Math.pow(7, 2); document.write("Power Value : " + value ); </script> </body> </html> Output : Power Value : 49
  • 43. Math.round() This method returns the value of a number rounded to the nearest integer. Syntax : Math.round(x); Example : <html> <head> <title>JavaScript Math sqrt() Method</title> </head> <body> <script type="text/javascript"> var value1 = Math.round(10.3); var value2 = Math.round(10.7); document.write(“Rounded Value1 : " + value1 + ”<br>”); document.write(“Rounded Value2 : " + value2); </script> </body> </html> Output : Rounded Value1 : 10 Rounded Value2 : 11
  • 44. Math.ceil Example: <html> <head> <title>JavaScript Math ceil() Method</title> </head> <body> <script type="text/javascript"> var value = Math.ceil(45.95); document.write("First Test Value : " + value ); var value = Math.ceil(45.20); document.write("<br />Second Test Value : " + value ); var value = Math.ceil(-45.95); document.write("<br />Third Test Value : " + value ); var value = Math.ceil(-45.20); document.write("<br />Fourth Test Value : " + value ); </script> </body> </html>
  • 45.
  • 46. • The Array object lets you store multiple values in a single variable. It stores a fixed- size sequential collection of elements of the same type. • An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Syntax : var fruits = new Array( "apple", "orange", "mango" ); var qty = new Array(10,35,15,20,40); You can create array by simply assigning values as follows − var fruits = [ "apple", "orange", "mango" ]; Var qty = [10,35,15,20,40]; You will use ordinal numbers to access and to set values inside an array as follows. • fruits[0] is the first element qty[0] is the first element • fruits[1] is the second element qty[1] is the second element • fruits[2] is the third element qty[2] is the third element The Arrays Object
  • 47. arr.length property Javascript array length property returns an unsigned, 32-bit integer that specifies the number of elements in an array. Syntax : array.length Example : <html> <head> <title>JavaScript Array length Property</title> </head> <body> <script type="text/javascript"> var arr = new Array( 10, 20, 30 ); document.write(“Array length is : " + arr.length); </script> </body> </html> Output : Array length is : 3
  • 48. Method Description concat() Returns a new array comprised of this array joined with other array(s) and/or value(s). join() Joins all elements of an array into a string. pop() Removes the last element from an array and returns that element. push() Adds one or more elements to the end of an array and returns the new length of the array. reverse() Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first. sort() Represents the source code of an object Array Methods
  • 49. arr.concat() Returns a new array comprised of this array joined with other array(s) and/or value(s). Syntax : array.concat(value1, value2, ..., valueN); Example : <html> <head> <title>JavaScript Array concat Method</title> </head> <body> <script type="text/javascript"> var alpha = ["a", "b", "c"]; var numeric = [1, 2, 3]; var alphaNumeric = alpha.concat(numeric); document.write("alphaNumeric : " + alphaNumeric ); </script> </body> </html> Output : alphaNumeric : a,b,c,1,2,3
  • 50. arr.join() Javascript array join() method joins all the elements of an array into a string. Syntax : array.join(separator); Example : <html> <head> <title>JavaScript Array join Method</title> </head> <body> <script type="text/javascript"> var arr = new Array("First","Second","Third"); var str = arr.join(“-"); document.write("<br />str : " + str ); </script> </body> </html> Output : str : First-Second-Third
  • 51. arr.push() Javascript array push() method appends the given element(s) in the last of the array and returns the length of the new array. Syntax : array.push(element1, ..., elementN); Example : <html> <head> <title>JavaScript Array push Method</title> </head> <body> <script type="text/javascript"> var numbers = new Array(1, 4, 9); var length = numbers.push(10); document.write("new numbers is : " + numbers ); </script> </body> </html> Output : new numbers is : 1,4,9,10
  • 52. arr.pop() Javascript array pop() method removes the last element from an array and returns that element. Syntax : array.pop(); Example : <html> <head> <title>JavaScript Array pop Method</title> </head> <body> <script type="text/javascript"> var numbers = [1, 4, 9]; var element = numbers.pop(); document.write("element is : " + element ); </script> </body> </html> Output : element is : 9
  • 53. arr.reverse() Javascript array reverse() method reverses the element of an array. The first array element becomes the last and the last becomes the first. Syntax : array.reverse(); Example : <html> <head> <title>JavaScript Array reverse Method</title> </head> <body> <script type="text/javascript"> var arr = [0, 1, 2, 3]; document.write("The array is : " + arr + "<br>"); document.write("Reversed array is : " + arr.reverse() ); </script> </body> </html> Output : The array is : 0,1,2,3 Reversed array is : 3,2,1,0
  • 54. arr.sort() Javascript array sort() method sorts the elements of an array. Syntax : array.sort(compareFunction); Where, compareFunction − Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically. Example : <html> <head> <title>JavaScript Array sort Method</title> </head> <body> <script type="text/javascript"> var arr = new Array(50,10,40,20,30); document.writeln("<p>Original array : " + arr); var sorted = arr.sort(); document.writeln("<p>Sorted array : " + sorted ); </script> </body> </html> Output : Original array : 50,10,40,20,30 Sorted array : 10,20,30,40,50
  • 55. • JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page. • When the page loads, it is called an event. When the user clicks a button, that click too is an event. • Other examples include events like pressing any key, closing a window, resizing a window, etc. • Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable. • Some of the most commonly used events are: • onLoad - occurs when a page/object loads in a browser • onUnload - occurs just before the user exits a page • onClick - occurs when an object is clicked • onSubmit - occurs when you submit a form • onMouseOver - occurs when you point to an object • onMouseOut - occurs when you point away from an object JavaScript Events
  • 56. onLoad event • The onload event occurs when an object has been loaded. • The onload is most often used within the <body> element to execute a script once a web page has completely loaded all content. • The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. Syntax : In HTML: <element onload="myScript"> In JavaScript: object.onload=function(){myScript};
  • 57. Example : <html> <head> <script type="text/javascript"> function myFunction() { alert("Page is loaded"); } </script> </head> <body onload="myFunction()"> <h1>onLoad Event!</h1> </body> </html>
  • 58. onUnload event • The onunload event occurs once a page has unloaded (or the browser window has been closed). • onunload occurs when the user navigates away from the page (by clicking on a link, submitting a form, closing the browser window, etc.). Syntax : In HTML: <element onunload="myScript"> In JavaScript: object.onunload=function(){myScript};
  • 59. Example : <html> <head> <script type="text/javascript"> function myFunction() { alert("Page is unloaded"); } </script> </head> <body onUnload="myFunction()"> <h1>onUnload Event!</h1> </body> </html>
  • 60. onClick event • This is the most frequently used event type which occurs when a user clicks the left button of his mouse. • You can put your validation, warning etc., against this event type. Syntax : In HTML: <element onClick="myScript"> In JavaScript: object.onClick=function(){myScript};
  • 61. Example : <html> <head> <script type="text/javascript"> function sayHello() { alert("Hello World") } </script> </head> <body> <h1>onClick Event!</h1> <p>Click the following button and see result</p> <form> <input type="button" onclick="sayHello()" value="Say Hello" /> </form> </body> </html>
  • 62. onSubmit event • onsubmit is an event that occurs when you try to submit a form. • You can put your form validation against this event type. Syntax : In HTML: <element onSubmit="myScript"> In JavaScript: object.onSubmit=function(){myScript};
  • 63. Example : <html> <head> <script type="text/javascript"> function myFunction() { alert("The form was submitted"); } </script> </head> <body> <h1>onSlick Event!</h1> <p>When you submit the form, a function is triggered which alerts some text.</p> <form action="demo_form.asp" onsubmit="myFunction()"> Enter name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form> </body> </html>
  • 64. onMouseOver and onMouseOut event • These two event types will help you create nice effects with images or even with text as well. • The onMouseOver event triggers when you bring your mouse over any element and the onMouseOut triggers when you move your mouse out from that element. Syntax : In HTML: <element onMounseOver="myScript"> In JavaScript: object.onMouseOver=function(){myScript}; In HTML: <element onMounseOut="myScript"> In JavaScript: object.onMouseOut=function(){myScript};
  • 65. Example : <html> <head> <script> function bigImg(x) { x.style.height = "64px"; x.style.width = "64px"; } function normalImg(x) { x.style.height = "32px"; x.style.width = "32px"; } </script> </head> <body> <h1>onMouseOver and onMouseOut Event!</h1> <img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0" src="smiley.gif" alt="Smiley“ width="32" height="32"> <p>The function bigImg() is triggered when the user moves the mouse pointer over the image.</p> <p>The function normalImg() is triggered when the mouse pointer is moved out of the image.</p> </body> </html>
  • 66. Small project - Image slideshow
  • 67. <html> <head> <script type="text/javascript"> var slideimages = new Array() // create new array to preload images slideimages[0] = new Image() // create new instance of image object slideimages[0].src = “image1.gif" // set image src property to image path, //preloading image in the process slideimages[1] = new Image() slideimages[1].src = “image2.gif" slideimages[2] = new Image() slideimages[2].src = “image3.gif" </script> </head> <body> <img src=“image1.gif" id="slide" width="200" height="100" /> <script type="text/javascript"> var step=0 //variable that will increment through the images function slideit() { if (!document.images) return document.getElementById('slide').src = slideimages[step].src if (step<2) step++ else step=0 setTimeout("slideit()",1000) //call function "slideit()" every 1 seconds } slideit() </script> </body> </html>
  • 69. TRAINING PROGRAMME FOR VOCATIONAL TEACHERS ON IT APPLICATIONS (CLASS XII) DATES: 06/06/2016 TO 15/06/2016 VENUE: SCERT COORDINATOR: DR. NARESH KAPOOR STATE COUNCIL OF EDUCATIONAL RESEARCH & TRAINING VARUN MARG, DEFENCE COLONY, NEW DELHI