160
JAVA SCRIPT

JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Embed Size (px)

Citation preview

Page 1: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

JAVA SCRIPT

Page 2: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

1. JavaScript was created by Brendan Eich and it came intoexistence in September 1995, when Netscape 2.0 (a web browser)was released.

2. JavaScript is one of the popular scripting Languagesdesigned with a purpose to make web pages dynamic and moreinteractive.

Page 3: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Advantages / Features :

1) It can be used for client and server applications.2) It is platform independent which means it can run on any

operating systems (i.e. Linux, Microsoft Windows, Mac OSX etc.).

3) JavaScript codes are needed to be embedded orreferenced into HTML documents then only it can run on aweb browser.

4) It is an interpreted language.5) It is a case-sensitive language and its keywords are in

lowercase only.

Page 4: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

DIFFERENCE BETWEEN JAVA AND JAVASCRIPT

Both are two completely different languages.

Java is a general-purpose object oriented programming languagefrom Sun Microsystems where asJavaScript is an object-based scripting language. Script refers toshort programming statements to perform a task.

Client Side Scripting lang- Java Script, VB script, DHTML

Server- Side Scripting lang- ASP,PHP(hypertext pre processor),phython, CGI, perl

Page 5: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

JavaScript is not a full-fledged language and it needs to be embeddedwithin a HTML document.

• JavaScript can be implemented using JavaScript statements that areplaced within the <script>... </script> HTML tags in a web page.

• We can place our JavaScript code in either the HEAD or BODY sectionof a HTML document.

Attribute Value DescriptionType text/javascript the type of scriptLanguage Javascript name of scripting language

Src URL a URL to a file that contains the script

Page 6: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<HTML><HEAD><TITLE>My First JavaScript program</TITLE></HEAD><BODY><SCRIPT type=”text/javascript” >document.write(“Welcome toJavaScript Programming!”);</SCRIPT></BODY></HTML>

<script language="javascript" type="text/javascript">

Page 7: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Tools needed for Writing and RunningJavaScript code :Following tools are needed for working with JavaScriptcode:a) Text Editors: We can choose any text editor or word

processor (i.e. Notepad, Wordpad etc.).

b) Browser: Browser interprets JavaScript code and showsthe output on browser’s document window.

Page 8: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

PLACING THE JAVASCRIPT CODE

There are two ways to place the JavaScript code :1. Embedded/Inline JavaScript : JavaScript code can be placed eitherin the HEAD or in the BODY section of a HTML document.a. It is advised to place JavaScript code in HEAD section when it is requiredto be used more than once.b. If the JavaScript code is small in size and used only once, it is advisable toput it in the BODY section of the HTML document.

2. External JavaScript : In case, same JavaScript code needs to be used inmultiple documents then it is the best approach to place JavaScript code inexternal files having extension as . .js..To do so, we will use src attribute in <SCRIPT> tag to indicate the link forthe source JavaScript file.

Page 9: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

illustration of the use of external JavaScript code.

HTML><HEAD><TITLE>Using External JavaScript</TITLE></HEAD><BODY><SCRIPT language=“JavaScript” type=“text/javascript” src=“abc.js”></SCRIPT><P> The actual JavaScript code exists in external file called“abc.js”. </P></BODY></HTML>

Page 10: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers
Page 11: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

STATEMENTS IN JAVASCRIPT

Statements are the commands or instructions given to the JavaScript interpreter to takesome actions as directed.A JavaScript interpreter resides within almost Internet browsers.

A collection of statements to accomplish a job, is called as a script or program.

a = 100; // stores value 100 in variable ab = 200; // stores value 200 in variable bc = a + b; // stores the sum of a and b in variable cdocument.write (“Sum of A and B : “); // displays the stringdocument.write(c); // displays the value of c

Page 12: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

In JavaScript, semicolon(;) is used to end a statement but iftwo statements are written in separate lines then semicolon canbe omitted.Some valid statements are :(i) p=10q=20(ii) x=12; y=25 // semicolon(;) separating two statements.Some invalid statements are :x=12 y=25 // statements within the same line not separated by semicolon (;)

Page 13: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

COMMENTSComments are the statements that are always ignored by the interpreter.They are used to give remarks to the statement making it more readableand understandable to other programmers.

There are two types ofcomments :- Single line comment using double-slash (//).- Multiple lines comment using /* and */ .

For example :// This is a single-line comment./* This is a multiple-line comment.It can be of any length. */<b><u>APS</u></b>

Page 14: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

LITERALSLiterals refer to the constant values, which areused directly inJavaScript code. For example:a=10;b=5.7;document.write(“Welcome”);In above statements 10, 5.7, “Welcome” are literals.

Page 15: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Identifiers refer to the name of variables, functions, arrays, etc. createdby the programmer. It may be any sequence of characters in uppercase andlowercase letters including numbers or underscore and dollar sign.

• An identifier must not begin with a number.• cannot have same name as any of the keywords

of the JavaScript.• A variable name must start with a letter, underscore

(_), or dollar sign ($). The subsequent.• Characters can be the digits (0-9).• JavaScript is case sensitive, so the variable name

my_school is not the same as My_School.

Page 16: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Some valid identifiers are :RollNo

bus_fee

_vp

$amt

Some invalid identifiers are :

to day // Space is not allowed

17nov // must not begin with a number

%age // no special character is allowed

Page 17: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

RESERVED WORDS OR KEYWORDSReserved words are used to give instructions to theJavaScript interpreter and every reserved word has aspecific meaning.These cannot be used as identifiers in theprogram.This means, we cannot use reserved words as names for variables,arrays, objects, functionsand so on.These words are also known as ‘Keywords’.

Page 18: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

VARIABLES

A variable is an identifier that can store valuesor

It is a named storage location.• Variable declaration is not compulsory.• Keyword var is used to declare a variable.Syntaxvar var-name [= value]

Examplevar name = “Sachin”; // Here name is variabledocument.write(name); // Prints Sachin

Page 19: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

A JavaScript variable can hold a value of any data type.

For example :i = 7;document.write(i); // prints 7

i = “seven”; // JavaScript allows to assign string valuesdocument.write(i); // prints seven

Some valid examples of variable declaration:var cost;var num, cust_no = 0;var amount = 2000;

Page 20: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Some valid variable namesf_nameIndia123_sumof

Some invalid variable names10_numbers // must not begin with any number.rate% // “%” is not a valid character.my name //Space is not allowed.

Page 21: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

JavaScript Variable ScopeThe scope of a variable is the region of your program in which it isdefined. JavaScript variables have only two scopes.

Global Variables: A global variable has global scope which meansit can be defined anywhere in your JavaScript code.

Local Variables: A local variable will be visible only within afunction where it is defined. Function parameters are always local tothat function.

Page 22: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<script type="text/javascript"><!--var myVar = "global"; // Declare a global variablefunction checkscope( ) {var myVar = "local"; // Declare a local variabledocument.write(myVar);}//--></script>

Within the body of a function, a local variable takesprecedence over a global variable with the same name.

If you declare a local variable or function parameter with the samename as a global variable, you effectively hide the global variable.

Page 23: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Program js3.html : To find the sum of two numbers using var.

<HTML><HEAD><TITLE>Sum of two numbers</TITLE></HEAD><BODY><SCRIPT type="text/javascript">var a = parseInt(prompt(“Enter any integer”));var b = 500;var c = a + b;document.write ("Sum of a & b = " + c );</SCRIPT></BODY></HTML>

Page 24: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

DATA TYPES:

javascript support number, string, boolean, array, object, null, undefined data types.

javascript is a loosely typed language. What this means is that you can use the samevariable for different types of information.

Example :var x; //now x is undefinedx = 'ram'; //now x is a stringx = 30; //now x is a number

x=null ; // now x is empty or null

primitive data types : number , string , boolean

complex types: array, object

special data types: null , undefined

Page 25: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

JavaScript supports three basic data types : number, string, booleanand two composite data types : arrays and objects.

1 numberThe number variable holds any type of number, either an integer or a realnumber.

Some examples of numbers are:29, -43, 3.40, 3.4323

Page 26: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

2 STRINGA string is a collection of letters, digits, punctuationcharacters, and so on. A string literal is enclosed withinsingle quotes or double quotes .

Examples of string literals are:

‘welcome’“7.86”“wouldn’t you exit now”‘country=“India”’

Page 27: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

An escape sequence

Combination of backslash(\) and a character whose effectis interpreted at run time.

This backslash tells browser to represent a special action or characterrepresentation.

For example “\n” is an escape sequence that represents a new line.

Page 28: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Escape Sequence Action/ Character Represented

\b Backspace\n New line\r Carriage return\t Tab\’ Single quote ( ‘)\” Double quote (“)\\ Backslash (\)

Page 29: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

3. BOOLEAN VALUESA boolean variable can store only two possible values either true orfalse. Internally it is stored as 1 for true and 0 for false.It is used to get the output of conditions, whether a condition results in trueor false.

Examplex == 100; // results true if x=100 otherwise false.

Page 30: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

javascript undefined or null

The javascript undefined value is returned when you use an object property that doesnot exist, or a variable that has been declared, but has never had a value assigned to it.

The javascript null value means the value has been set to be empty.

Example:<script>

var name ;var empty = null;

document.write(name);document.write("<br/>"+"-----"+empty);

</script>

Page 31: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

An array is a collection of data values of a types having acommon name.

• Each data element in array is referenced by its positionin the array also called its index number.

• Individual array elements can be referenced by the array

name followed by the pair of square brackets having itsindex number.• The index number starts with zero in JavaScript i.e. the

first element in JavaScript has it index value as 0, second hasits index value as 1 and so on.

An array

Page 32: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

An array can be declared in any of the following ways :var a = new a( );

var x = [ ];var m = [2,4.5,”sun”];

An array is initialised with the specified values as its elements,and its length is set to the number of arguments specified.

Example This creates an array name games with three elements.var games= new games();games = [‘Hockey’,’Cricket’, ‘Football’];

games[0];We can also store different types of values in an array.

For example :var arr = new Array(); // creation of an arrayarr[0] =”JAVASCIPT”; // stores String literal at index 0arr[1] = 49.5; // stores real number at index 1arr[2] = true; // stores Boolean value

Page 33: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

We can create array by simply assigning values as follows −

var fruits = [ "apple", "orange", "mango" ];

fruits[0] is the first elementfruits[1] is the second elementfruits[2] is the third element

Array PropertiesProperty Description

constructor Returns a reference to the array function that created the object.

index The property represents the zero-based index of the match in thestring

length Reflects the number of elements in an array.

prototype The prototype property allows you to add properties and methodsto an object.

Page 34: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Array Methods

1 concat() methodJavascript array concat() method returns a new array comprisedof this array joined with two or more arrays.

The syntax of concat() method is as follows −array.concat(value1, value2, ..., valueN);

<script type="text/javascript">var alpha = ["a", "b", "c"];var numeric = [1, 2, 3];

var alphaNumeric = alpha.concat(numeric);document.write("alphaNumeric : " + alphaNumeric );

</script>

alphaNumeric : a,b,c,1,2,3alphaNumeric : a,b,c,1,2,3

Page 35: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

2 indexOf()Returns the first (least) index of an element within the

array equal to the specified value, or -1 if none is found.

var index = [12, 5, 8, 130, 44].indexOf(8);document.write("index is : " + index );

var index = [12, 5, 8, 130, 44].indexOf(13);document.write("<br />index is : " + index );

index is : 2index is : -1index is : 2index is : -1

Page 36: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

3 Array join() MethodJavascript array join() method joins all the elements of anarray into a string.

Its syntax is as follows −array.join(separator);

Whereseparator − Specifies a string toseparate each element of the array.If omitted, the array elements areseparated with a comma.

Its syntax is as follows −array.join(separator);

Whereseparator − Specifies a string toseparate each element of the array.If omitted, the array elements areseparated with a comma.

<script type="text/javascript">var arr = new Array("First","Second","Third");

var str = arr.join();document.write("str : " + str );

var str = arr.join(", ");document.write("<br />str : " + str );

var str = arr.join(" + ");document.write("<br />str : " + str );

</script>

str : First,Second,Thirdstr : First, Second, Thirdstr : First + Second + Third

str : First,Second,Thirdstr : First, Second, Thirdstr : First + Second + Third

Page 37: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

4 lastIndexOf()Returns the last (greatest) index of an element within the

array equal to the specified value, or -1 if none is found.

var index = [12, 25, 8, 130, 4,8,15].lastIndexOf(5);document.write("index is : " + index );

var index = [12, 5, 8, 130, 44, 5].lastIndexOf(5);document.write("<br />index is : " + index );

index is : -1index is : 5index is : -1index is : 5

Page 38: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Javascript array map() method creates a new array with theresults of calling a provided function on every element in thisarray.

var numbers = [1, 4, 9];var roots = numbers.map(Math.sqrt);document.write("roots is : " + roots );

roots is : 1,2,3roots is : 1,2,3

Page 39: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

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.

<script type="text/javascript">var numbers = [1, 4, 9];

var element = numbers.pop();document.write(element );var element = numbers.pop();

document.write("<br /> " + element );</script>

9494

<script type="text/javascript">var numbers = new Array(1, 4, 9);

var length = numbers.push(10);document.write(numbers );

length = numbers.push(20);document.write("<br />”+ numbers );

</script>

1,4,9,101,4,9,10,201,4,9,101,4,9,10,20

Page 40: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Javascript array slice() method extracts a section of an array andreturns a new array.Its syntax is as follows −array.slice( begin [,end] );

<script type="text/javascript">var arr = ["orange", "mango", "banana", "sugar", "tea"];

document.write("arr.slice( 1, 2) : " + arr.slice( 1, 2) );

document.write("<br />arr.slice( 1, 3) : " + arr.slice( 1, 3) );

</script>

arr.slice( 1, 2) : mangoarr.slice( 1, 3) : mango,bananaarr.slice( 1, 2) : mangoarr.slice( 1, 3) : mango,banana

Page 41: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Javascript array splice() method changes the content of an array,adding new elements while removing old elements.

array.splice(index, howMany, [element1][, ..., elementN]);

index − Index at which to start changing the array.

howManyhowMany is 0, no elements are removed.

element1, ..., elementN − The elements to add to the array. If you don't specify anyelements, splice simply removes the elements from the array.

Page 42: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<script type="text/javascript">var arr = ["orange", "mango", "banana", "sugar", "tea"];

var removed = arr.splice(2, 0, "water");document.write(arr );

document.write("<br />removed is: " + removed);

removed= arr.splice(3, 1);document.write("<br /> " + arr );document.write("<br />removed is: " + removed);

</script>

orange,mango,water,banana,sugar,tearemoved is:orange,mango,water,sugar,tearemoved is: banana

orange,mango,water,banana,sugar,tearemoved is:orange,mango,water,sugar,tearemoved is: banana

Page 43: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Javascript array sort() method sorts the elements of an array.

<script type="text/javascript">var arr = new Array("orange", "mango", "banana", "sugar");

var sorted = arr.sort();document.write("Returned string is : " + sorted );

</script>

Returned array is :banana,mango,orange,sugarReturned array is :banana,mango,orange,sugar

Page 44: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

The eval() function evaluates or executes anargument.

<html><body><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() {

var x = 10;var y = 20;var a = eval("x * y");var b = eval("2 + 2");var c = eval("x + 17");var res = a + b + c;document.write(res);//document.getElementById("demo").innerHTML = res;

}</script></body></html>

Page 45: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

NULL VALUEJavaScript supports a special data type known as null that indicates.no value or blank.. Note that null is not equal to 0.Examplevar distance = new object();Distance=null;

OBJECTSJavaScript is an object based scripting language.It allows us to define our own objects and make our own variable types.

It also offers a set of predefined objects. The tables, forms,buttons, images,or links on our web page are examples of objects.

The values associated with object are properties and the actions that canperform on objects are methods or behaviour.

Property associated to an object can be accessed as follows:ObjectName.PropertyName

Page 46: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

DOCUMENT OBJECT

1. The Document object is one of the parts of the Windowobject.

2. It can be accessed through the window.documentproperty.

3. The document object represents a HTML document andit allows one to access all the elements in a HTMLdocument.

For example: title of current document can beaccessed by document.title property.

Page 47: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Some of the common properties of document object are :

Page 48: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Methods Purposes

1 open() Opens a document for writing.

2 write() Writes string/data to a document.

3. writeln() Writes string/data followed by anewline character to a document.

4 close() Closes a document stream forwriting.

Page 49: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Program j4.html : To illustrate the properties and methods of the document object.<HTML><HEAD> <TITLE>Document Properties</TITLE> </HEAD><BODY><H1> To illustrate the properties and methods of the document object.</H1><script>document.write("hi");document.fgColor="navy"; //sets the text colour to bluedocument.bgColor="wheat"; //sets the background colour to yellowdocument.title="India";document.width="1000";document.write("<br>the width of current document is " + document.width);</script><p><h2>Note that write() does NOT add a new line after each statement:</h2></p><pre> <script>document.write("Hello World!");document.write("Have a nice day!");</script> </pre><p><h2>Note that writeln() add a new line after each statement:</h2></p><pre> <script>document.writeln("Hello World!");document.writeln("Have a nice day!");</script> </pre> </BODY></HTML>

Page 50: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

2. DATE OBJECT

• This object is used to set and manipulate date and time.• JavaScript dates are stored as the number of milliseconds

since midnight, January 1, 1970. This date is called theepoch.

• Dates before 1970 are represented by negative numbers.

A date object can be created by using the new keyword with Date().

Syntax

newDate()new Date(milliseconds)new Date(dateString) // e.g. “October 5, 2007”new Date(yr_num, mo_num, day_num)

Page 51: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Different examples of using a date()today = new Date();dob = new Date(“October 5, 2007 12:50:00”);doj = new Date(2007,10,5);bday = new Date(2007,10,5,12,50,0);

Page 52: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Methods to read date valuesWe can use the get methods to get values from a Date object.

Method DescriptionDate() Returns today's date and timegetDate() Returns the day of the month for the specified date

according to local time.getDay() Returns the day of the week for the specified date

according to local time.getFullYear() Returns the year of the specified date according to local

time.getHours() Returns the hour in the specified date according to local

time.getMilliseconds() Returns the milliseconds in the specified date

according to local time.getMinutes() Returns the minutes in the specified date according to

local time.getMonth() Returns the month in the specified date according to local

time.getSeconds() Returns the seconds in the specified date according to

local time.getTime() Returns the numeric value of the specified date as thenumber of milliseconds since January 1, 1970, 00:00:00 UTC.

Page 53: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Program js5.html : A simple JavaScript program that displays today’s date andcurrent time.

<HTML><HEAD><TITLE>Displaying Time</TITLE></HEAD><BODY><CENTER><H1>Today’s Date and Current Time</H1></CENTER><SCRIPT type=“text/javascript”>var today = new Date();/* we can use html formatting tags with document.write */document.write(“<H2>”);document.write(today);document.write(“</H2>”);</SCRIPT></BODY></HTML>

Page 54: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<HTML><HEAD><TITLE>Displaying Time</TITLE></HEAD> <BODY><CENTER><H1>Today’s Date and Current Time</H1></CENTER><SCRIPT type="text/javascript">var dt = new Date();/* we can use html formatting tags with document.write */document.write("<H2>");document.write("Date():"+dt);document.write("</H2> <br>");document.write("getDate() : " + dt.getDate() );document.write("<br>");document.write("getDay() : " + dt.getDay() );document.write("<br>");

document.write("getHours() : " + dt.getHours() );document.write("<br>");document.write("getFullYear() : " + dt.getFullYear() );document.write("<br>");document.write("getMilliseconds() : " + dt.getMilliseconds() );</SCRIPT></BODY> </HTML>

Page 55: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

• The math object provides you properties and methods for

mathematical constants and functions.

• Unlike other global objects, Math is not a constructor.

• All the properties and methods of Math are static and can be called by

using Math as an object without creating it.

The math object

Thus, you refer to the constant pi as Math.PI and you call thesine function as Math.sin(x), where x is the method'sargument.

SyntaxThe syntax to call the properties and methods of Math are asfollows:var pi_val = Math.PI;var sine_val = Math.sin(30);

Page 56: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Math PropertiesHere is a list of all the properties of Math and their description.

Property Description

PI Ratio of the circumference of a circle to its diameter, approximately3.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

LN10 Natural logarithm of 10, approximately 2.302

Page 57: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

JS6.HTML

<html> <head> <title>JavaScript Math PI Property</title> </head><body><script type="text/javascript">var property_value = Math.SQRT2;document.write("Property Value is : " + property_value);</script></body> </html>

Page 58: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Math MethodsHere is a list of the methods associated with Math object and theirdescription.

METHOD DESCRIPTION

abs() Returns the absolute value of a number.ceil() Returns the smallest integer greater than or equal to a number .

floor () Returns the largest integer less than or equal to 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.

random () Returns a pseudo-random number between 0 and 1.

round() Returns the value of a number rounded to the nearest integer.

sqrt() Returns the square root of a number.

sin() Returns the sine of a number.

NaN : "Not-a-Number"

Page 59: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

js7.html<html><head><title>JavaScript Math abs() Method</title></head><body><script type="text/javascript">

var value = Math.abs(-1);document.write("First Test Value : " + value );

var value = Math.abs(null);document.write("<br />Second Test Value : " + value );

var value = Math.abs(20);document.write("<br />Third Test Value : " + value );

var value = Math.abs("string");document.write("<br />Fourth Test Value : " + value );

</script></body></html>

Page 60: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

ceil ( )This method returns the smallest integer greater than or equal to anumber.SyntaxIts syntax is as follows:Math.ceil ( x ) ;

js8.html

<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>

Page 61: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

EXPRESSIONSAND

OPERATORS

Page 62: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

An expression is a combination of operators& operands that can be evaluated.Examplesx = 7.5 // a numeric literal“Hello India!” // a string literalfalse // a Boolean literal{feet:10, inches:5} // an object literal[2,5,6,3,5,7] // an array literalv= m + n; // the variable v,m,n

Page 63: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

ARITHMETIC OPERATORSThese are used to perform arithmetic/mathematical operations likesubtraction, division, multiplication etc. Arithmetic operators work onone or more numerical values (either literals or variables) and returna single numerical value. The basic arithmetic operators are:

+ (Addition) - (Subtraction)* (Multiplication) / (Division)% (Modulus) ++ (Increment by 1)--(Decrement by 1)

Page 64: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Examples:

var s = 10 + 20; // result: s=30var h = 50 * 4; // result: h = 200var d = 100 / 4; // result: d = 25var r = 72 % 14; // result: r=2

Page 65: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Increment and decrement operatorsThese operators are used for increasing or decreasing the value of a variableby 1 respectively.. Calculations performed using these operators are veryfast.

Examplevar a = 15;a++; // result: a = 16a=a+1;var b = 20;b--; // result: b = 19

Page 66: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

operator description example result of x+ addition x = 5+y; 11- subtraction x = y-4 2* multiplication x = 4*y 24/ division x = y/2 3% modulus (remainder) x = y%2 0

++ increments a variable byone x = ++y 7

-- decrements a variable byone x = --y 5

javaScript arithmetic operatorsjavascript arithmetic operators are used to perform arithmetic operation betweenvariables and/or values.

The table below explains the arithmetic operators: where y=6:

Page 67: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Assignment Operator

Page 68: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<html> <head> <title> operators </title> </head><body>

<script>function output()

{var a =40;var b ="ram kumar";var c =true;var x= y = z =50; //multiple assignments

var output = (a*x)+(y-z);document.write("the output is ____"+output);document.write("<br/>the a value\’ ______"+ a );document.write("<br/>the b value ______"+ b );

document.write("<br/>the c value ______"+ c );document.write("<br/>the x y z values ______"+ x +"__"+y+"___"+z );}

output(); //this statement call the output method</script> </body> </html>

The assignment operator is used to assign a value to a single variable, but it is possible toperform multiple assignments at once by stringing them together with the = operator.

Page 69: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

RELATIONAL (COMPARISON) OPERATORS

The javascript comparison operators are used to compare two values.it can be used inlogical statements.The result of a comparison operation is always true or false.given that x = 4, the table below explains the comparison operators:

operator description example returns< less than x < 4 false> greater than x > 4 false<= less than or equal to x <= 4 true>= greater than or equal to x >=4 true== equal to x == 4 true=== equal to (strict equality) x === 4 true=== equal to (strict equality) x === ‘4’ false!= not equal x != 5 true!== not equal (strict inequality) x !== 4 false!== not equal (strict inequality) x !== ‘4’ true

Page 70: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

note :- (===) and (!==) operators behave the same as theequality operators(== and !=), but the both operands type must match.

a strict comparison (===,!==) is only true if the operands are the same type.

comparing strings :- when you compare strings, javascript evaluates thecomparison based on strings lexicographic order.

lexicographic order is essentially alphabetic order, with a few extra rules thrown into deal with upper-case and lower-case characters as well as to accommodatestrings of different lengths.the following general rules apply:•lowercase characters are less than uppercase characters.•shorter strings are less than longer strings.•letters occurring earlier in the alphabet are less than those occurring later.•characters with lower ascii or unicode are less than those with larger values.

Page 71: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

LOGICAL OPERATORS

Page 72: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

operator description example returns&& logical and operator if(20>=10&&10==10) true|| logical or operator if(4!==4 || 5<6) true! logical not operator !(12==12) false

Page 73: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

CONCATENATION OPERATOR

The + operator concatenates two string operands. The +operator gives priority to string operands over numericoperands It works from left to right. The results depend on theorder in which operations are performed.For example :Statement Output“Good” + “Morning” “GoodMorning”“5” + “10” “510”“Lucky” + 7 “Lucky7”4 + 7 + “Delhi” “11Delhi”

Page 74: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Conditional Operator ( ? : )The conditional operator is a special JavaScript operatorthat takes three operands. Hence, it is also called ternaryoperator. A conditional operator assigns a value to avariable based on the condition.

Syntaxvar_name = (condition) ? v_1 : v_2;If (condition) is true, the value v_1 is assigned to the variable,otherwise, it assigns the value v_2 to the variable.For examplestatus = (age >= 18) ? “adult” : “minor”;This statement assigns the value “adult” to the variable status ifage is eighteen or more. Otherwise, it assigns the value “minor” tostatus.

Page 75: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<html><head>

<title> Ternary operator </title></head>

<body><script>

function ternary(){var a = (20 >= 19) ? 20 : 19;

alert("a value ="+a);

(5 > 4 && 4 == 4) ? alert("this is true part") : alert("this is the false part");

}</script><button onclick="ternary()"> please click </button>

</body></html>

Page 76: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

javaScript comma operator

the comma(,) operator allows multiple expressions to be evaluated in a single statement andreturns the result of the last expression.

<html> <head> <title> comma operator </title> </head><body>

<script>

var x, y, z,a;

x = (a=3,y=50, z=60+y,a);

document.write('x = '+x+ "____“ + 'y = ' +y + "_____"+' z = ' +z);

</script> </body></html>

Page 77: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<html><head> <title> typeof operator in javascript </title> </head><body><script>

var first_value = 2000; var second_value =33300.333;var third_value=3434e3;var first_string="javascript type of operator";var second_string = "what is typeof";

document.write("<br/>"+"type of first_value is_"+typeof(first_value)+

"<br/>"+"type of second_value is________"+typeof(second_value)+

"<br/>"+"type of third_value is________"+typeof(third_value)+

"<br/>"+"type of first_string is________"+typeof(first_string)+

"<br/>"+"type of second_string is________"+typeof(second_string)+

"<br/>"+"type of third_string is________"+typeof(third_string));</script> </body> </html>

The javascript typeof operator returns a string indicating the data type of its operand

Page 78: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers
Page 79: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

DOMEvery web page resides inside a browser window whichcan be considered as an object.( Web page or source code)

A Document object represents the HTML document that isdisplayed in that window.

Page 80: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

The way a document content is accessed and modified is called theDocument Object Model, or DOM.The Objects are organized in a hierarchy. This hierarchical structureapplies to the organization of objects in a Web document.a. Window object − Top of the hierarchy. It is the outmost

element of the object hierarchy.b. Document object − Each HTML document that gets loaded into

a window becomes a document object. The document containsthe contents of the page.

c. Form object − Everything enclosed in the <form>...</form>tags sets the form object.

d. Form control elements − The form object contains all theelements defined for that object such as text fields, buttons,radio buttons, and checkboxes.

Page 81: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Here is a simple hierarchy of a few important objects:

Page 82: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

The window object, which is a top-level object in ClientSide JavaScript, represents a window or a frame (within aframeset). Since window object is a top-level object, itcontains other objects like 'document', 'history' etc.within it.

For example, window.document.frames[i], where i is1,2,3....., refers to the index of the frame residing in thecurrent window.

The window object

Page 83: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

An object of window is created automatically by thebrowser.Window is the object of browser, it is not theobject of javascript.

The javascript objects are string, array, date etc.

Note: if html document contains frame or iframe, browsercreates additional window objects for each frame.

Page 84: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Method Description

alert() displays the alert box containing message with okbutton.

confirm() displays the confirm dialog box containingmessage with ok and cancel button.

prompt() displays a dialog box to get input from the user.

open() opens the new window.

close() closes the current window.

setTimeout() performs action after specified time like callingfunction, evaluating expressions etc.

Methods of window objectThe important methods of window object are as follows:

Page 85: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Example of alert() in javascriptIt displays alert dialog box. It has message and ok button.

<script type="text/javascript">function msg(){alert("Hello Alert Box");}</script><input type="button" value="click" onclick="msg()"/>

Page 86: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<script type="text/javascript">function msg(){var v= confirm("Are u sure?");

if(v==true) {alert("ok");

}else {

alert("cancel"); }}</script>

<input type="button" value="delete record" onclick="msg()"/>

Page 87: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<script type="text/javascript">function msg(){var v= prompt("Who are you?");alert("I am "+v);

}</script>

<input type="button" value="click" onclick="msg()"/>

Page 88: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Example of open() in javascriptIt displays the content in a new window.

<script type="text/javascript">function msg(){open("http://www.google.com");}</script>

<input type="button" value=“Google” onclick="msg()"/>

Page 89: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Example of setTimeout() in javascriptIt performs its task after the given milliseconds.

<script type="text/javascript">function msg(){setTimeout( function(){ alert("Welcome to Javatpoint after 2 seconds") },2000);

}</script>

<input type="button" value="click" onclick="msg()"/>

Page 90: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

JAVASCRIPT POPUP BOXES(DIALOG BOXES)

JAVASCRIPT POPUP BOXES(DIALOG BOXES)

Page 91: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

In JavaScript, three kinds of popup boxes . Alert box, Confirm box, andPrompt box can be created using three methods of window object.

ALERT BOXAlert( ) method of window object creates a small dialogbox with a short text message and “OK” commandbutton called alert box. Alert box contains an iconindicating a warning.Syntax[window].alert(“Text to be displayed on the popup box”);The word window is optional.

Page 92: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Examplewindow.alert(“I am to alert you about ….”);oralert(“I am to alert you about ….”);OutputAn alert box is used if we wantto display some information to theuser. When an alert box appears,the user needs to click .OK. buttonto proceed.

Page 93: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

CONFIRM BOXConfirm box is used if we want the user to verifyand confirm theinformation. The user will have to click either “OK”or “Cancel” buttons.Syntax[window].confirm(“Text to be confirmed”);Exampleconfirm(“Do you want to quit now?”);

Page 94: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

PROMPT BOXPrompt box allows getting input fromthe user. We can specify the default textfor the text field. The informationsubmitted by the user from prompt( ) canbe stored ina variable.

Syntaxprompt(“Message” [, “default value in the text field”]);

Page 95: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Examplevar name = prompt(“What’s your name?”, “Your name please…”);OutputA prompt box returns input string valuewhen the user clicks .OK.. If the userclicks .Cancel., it returns null value.

Page 96: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

The window.history object contains information about theurls(uniform resource locator) visited by the client.By using this object, you can load previous, forward or any

particular page.

The history object is the window property, so it can be accessedby: window.history or history

Page 97: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Property of JavaScript history object

There is only 1 property of history object.

No. Property Description

1 length returns the length of the history URLs.

<script>

document.write('number of urls evaluates with history ='+history.length);

</script>

Page 98: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

No. Method Description

1 forward() loads the next page.2 back() loads the previous page.3 go() loads the given page number.

Methods of JavaScript history objectThere are only 3 methods of history object.

history.back();//for previous page

history.forward();//for next page

history.go(2);//for next 2nd page

history.go(-2);//for previous 2nd page

Page 99: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<html><head>

<title> back the url </title></head>

<body><script>

function back_url(){ window.history.back() ; }

</script>

<button onclick="back_url()" >click here back the url </button>

</body></html>

Page 100: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<html><head>

<title> forward the url </title></head>

<body>

<script>

function forward_url(){ window.history.forward() ; }

</script>

<button onclick="forward_url()" >click here forward the url </button>

</body></html>

Page 101: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Example: click on this button to go back three pages:

<script>

function go_url(){

window.history.go(-3) ;}

</script>

<button onclick="go_url()" > go third web page backward </button>

Page 102: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

javaScript location object

The window.location object contains information about thecurrent url .

The window.location returns a location object, whichcontains information about the url of the document andprovides methods for changing that url.

The window.location object can be written without the windowperfix.

syntax:var url_info = window.location

Page 103: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

property description

hash sets or returns the subsection of the href property that follows thesign(#)

host sets or returns the hostname and port of the location or the url.

hostname sets or returns the host name part of the location or url

href sets or returns the entire url as a string

pathname sets or returns the file name or path specified by the object

port sets or returns the port number associated with a url

protocol sets or returns the protocol portion of a url

search sets or returns the substring of the href property that follows themark(?)

JavaScript window location object propertieswindow.location object properties can be used to get information about thecurrent url or set them to navigate to another url.

The default property for the window.location object is location.href.

Page 104: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

example :display the properties of this url:

(http://www.example.com:8080/search?q=devmo#test).function property(){

// set the new urlwindow.location = "http://www.example.com:8080/search?q=devmo#test";

newlocation = window.location; //retrieves the location object

document.write("<br/>"+"hash ="+newlocation.hash) ;

document.write("<br/>"+"host ="+newlocation.host) ;

document.write("<br/>"+"hostname ="+newlocation.hostname) ;

document.write("<br/>"+"href ="+newlocation.href) ;

document.write("<br/>"+"pathname ="+newlocation.pathname);

document.write("<br/>"+"port ="+newlocation.port);

document.write("<br/>"+"protocol ="+newlocation.protocol) ;

document.write("<br/>"+"search ="+newlocation.search);}

Page 105: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

output: url(http://www.example.com:8080/search?q=devmo#test)

hash = #test

host = www.example.com:8080

hostname = www.example.com

href = http://www.example.com:8080/search?q=devmo#test

pathname = /search

port = 8080

protocol = http:

search = ?q=devmo

Page 106: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

JavaScript window.location object methods

1. The location.assign() method loads a new html document.

syntax:window.location.assign(stringurl);

stringurl : string that specifies the url of the document to load.

Page 107: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<html><head>

<title> load a new html document </title>

<script>function assign(){window.location.assign("http://www.google.co.in/?gws_rd=cr#bav=on.2");}

</script> </head><body><p><button onclick="assign()">load a new html doc</button></p>

</body> </html>

Page 108: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

2. location object reload() method

the location.reload() method reloads the current document.

syntax:

location.reload(true | false)

false : default.reloads the document from the cachetrue : reloads the document from the server

example : force reloading the current page from the server.

function reload(){

window.location.reload(true);

}

Page 109: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

3. location object replace() method

The location.replace() method replaces the current documentby loading another document at the specified url.

syntax:location.replace(newurl)

newurl : string that specifies the url .

function replace(){

window.location.replace("http://www.w3webtutorial.com") ;

}

Page 110: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

JavaScript Navigator Object

The JavaScript navigator object is used for browser detection. Itcan be used to get browser information such as appName,appCodeName, userAgent etc.

The navigator object is the window property, so it can be accessedby:

window.navigator

Page 111: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

No. Property Description1 appName returns the name2 appVersion returns the version3 appCodeName returns the code name4 cookieEnabled returns true if cookie is enabled otherwise false5 userAgent returns the user agent

6 language returns the language. It is supported in Netscape andFirefox only.

7 userLanguage returns the user language. It is supported in IE only.

8 plugins returns the plugins. It is supported in Netscape andFirefox only.

9 systemLanguage returns the system language. It is supported in IE only.

10 mimeTypes[] returns the array of mime type. It is supported inNetscape and Firefox only.

11 platform returns the platform e.g. Win32.12 online returns true if browser is online otherwise false.

Property of JavaScript navigator objectThere are many properties of navigator object that returns informationof the browser.

Page 112: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

html><body><h2>JavaScript Navigator Object</h2><script>

document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);

document.writeln("<br/>navigator.appName: "+navigator.appName);

document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);

document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);

document.writeln("<br/>navigator.language: "+navigator.language);

document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);

document.writeln("<br/>navigator.platform: "+navigator.platform);

document.writeln("<br/>navigator.onLine: "+navigator.onLine);</script></body></html>

Page 113: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

JavaScript Navigator Object

navigator.appCodeName: Mozilla

navigator.appName: Netscape

navigator.appVersion: 5.0 (Windows)

navigator.cookieEnabled: true

navigator.language: en-US

navigator.userAgent: Mozilla/5.0 (Windows NT 6.2; rv:53.0)

Gecko/20100101 Firefox/53.0

navigator.platform: Win32

navigator.onLine: true

Page 114: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

JavaScript Screen Object

The JavaScript screen object holds information of browser screen.It can be used to display screen width, height, colorDepth,pixelDepth etc.

The navigator object is the window property, so it can be accessedby:

window.screen

Page 115: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

No. Property Description1 width returns the width of the screen2 height returns the height of the screen3 availWidth returns the available width4 availHeight returns the available height5 colorDepth returns the color depth6 pixelDepth returns the pixel depth.

Property of JavaScript Screen ObjectThere are many properties of screen object that returns information of the browser.

Page 116: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers
Page 117: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

CONTROL STRUCTURESCONTROL STRUCTURES

ifif elseif else ifswicth case

whiledo whileforfor in

Page 118: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Functions

A function is a group of reusable code whichcan be called anywhere in your program. Thiseliminates the need of writing the same codeagain and again.

Ibulit functions or user defined functions.

Page 119: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

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.(function body)

Page 120: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

SyntaxThe basic syntax is shown here.<script type="text/javascript">

function functionname(parameter-list){Statements; // function body}

</script>

Page 121: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Examplelets create a function called sayHello that takes no parameters:

<script type="text/javascript">function sayHello(){alert("Hello there");}</script>

Page 122: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Calling a FunctionTo invoke/activate a function somewhere later in the script, youwould simply need to write the name of that function as givenbelow<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><p>Use different text in write method and then try...</p></body></html>

Page 123: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Function ParametersTill now, we have seen functions withoutparameters.But there is a facility to pass different parameterswhile calling a function.

These passed parameters can be captured inside thefunction

and any manipulation can be done over thoseparameters.

A function can take multiple parameters separated bycomma.

Page 124: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<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><p>Use different parameters inside the function and thentry...</p></body></html>

Page 125: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

The return StatementA 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.

For example, you can pass two numbers in a function and then you canexpect the function to return their multiplication / sum etc. in yourcalling program.

Page 126: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Example. It defines a function that takes two parameters andconcatenates them before returning the resultant in the calling program.

<html><head><script type="text/javascript">function concatenate(first, last){var full;full = first + last;return full;}function secondFunction(){var result;result = concatenate('Zara', 'Ali');document.write (result );}//secondFunction();</script></head>

Page 127: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<body><p>Click the following button to call thefunction</p><form><input type="button"onclick="secondFunction()" value="CallFunction"></form><p>Use different parameters inside thefunction and then try...</p></body></html>

Page 128: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Nested Functions

<html> <head> <script type="text/javascript">function hypotenuse(a, b){function square(x) { return x*x; }return Math.sqrt(square(a) + square(b));}function secondFunction(){var result;result = hypotenuse(3,2);document.write ( result );}</script> </head><body><p>Click the following button to call the function</p><form><input type="button" onclick="secondFunction()" value="CallFunction"> </form><p>Use different parameters inside the function and then try...</p></body> </html>

Page 129: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<HEAD><TITLE>A Simple JavaScript Function returning Value </TITLE><script language=“JavaScript” type= “text/JavaScript”>

function si( p, r, t ){ var s = (p * r * t)/ 100;return s; // function returning value s}</script></HEAD><BODY><script language=“JavaScript” type= “text/JavaScript”>var result = si( 1000, 5, 7) // returned value assigned to resultdocument.write ( “Result = ”+ result);

</script>

</BODY></HTML>

Page 130: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

var area, circumference;var r=10;with (Math){area = PI * r * rcircumference = 2*PI*r}with (document){write(“Area of the Circle: “+area+”<br>”);write(“Circumference of the Circle:”+circumference);}

Page 131: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

EVENTSEVENTS

Page 132: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Most JavaScript-applications perform actions as a response toevents.An event is a signal from the browser that somethinghas happened.There are many types of events.•DOM events, which are initiated by DOM-elements.For instance, a click event happens when an elementis clicked, a mouseover - when a mouse pointercomes over an element,•Window events. For instance, resize - when abrowser window is resized,•Other events, like load, readystatechange etc.

Page 133: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

When the page loads, it is called anevent.When the user clicks a button, thatclick too is an event.

Other examples include events likepressing any key, closing a window,resizing a window, etc.

Page 134: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Assigning event handlersFor a script to react on the event, there should be a functionassigned to it.Functions which react on events are called event handlers.

Page 135: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<html><head><script type="text/javascript">

function sayHello(){document.write ("Hello World")}</script></head><body><p> Click the following button and see result</p><input type="button" onclick="sayHello()" value="Say Hello" /></body></html>

onclick Event Type

Page 136: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

onsubmitEvent Type: onsubmit is an event that occurs when you tryto submit a form .

The following example shows how to use onsubmit. Here we arecalling a validate() function before submitting a form data to thewebserver. If validate() function returns true, the form will besubmitted, otherwise it will not submit the data.

<html> <head> <script type="text/javascript">function validation() {

all validation goes here.........return either true or false

}</script> </head>

<body><form method="POST" action="t.cgi" onsubmit="validation()">

.......<input type="submit" value="Submit" />

</form></body>

</html>

Page 137: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<input id="b1" value="Click me"onclick="alert('Thanks!');" type="button"/>

For example, to process a click event on the input button, it is possible to assign anonclick handler like this:

Page 138: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<html> <head> <script type="text/javascript">function count_rabbits()

{ for(var i=1; i<=3; i++){ alert("Rabbit "+i+" out of the hat!") }

}</script> </head><body>

<input type="button" onclick="count_rabbits()"value="Count rabbits!"/></body></html>

Page 139: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<input id="myElement" type="button" value="Press me"/><script>document.getElementById('myElement').onclick =function(){

alert('Thanks')}</script>

Page 140: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

onmouseover and onmouseoutThe onmouseover event triggers when you bringyour mouse over any element and

the onmouseout triggers when you move yourmouse out from that element.

Page 141: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<html> <head> <script type="text/javascript">

function over(){ document.write ("Mouse Over");

}function out(){ document.write ("Mouse Out");}</script> </head> <body>

<p>Bring your mouse inside the division to see the result:</p>

<div onmouseover="over()" onmouseout="out()"><h2> This is inside the division </h2> </div>

</body></html>

Page 142: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

HTML 5Standard Events

Page 143: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

ondrag script Triggers when an element is dragged

Page 144: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers
Page 145: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

Att Value Desconsubmit script Triggers when a form is

submitted

onsuspend script Triggers when the browser has beenfetching media data, but stopped beforethe entire media file was fetched

onunload script Triggers when the user leaves thedocument

onwaiting script Triggers when media has stoppedplaying, but is expected to resume

Page 146: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

JavaScript String

The JavaScript string is an object that represents a sequence of characters.

Strings are useful for holding data that can be represented in text form.

The string literal value enclosed in single(') or double(") quotes.

Page 147: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

There are 2 ways to create string in JavaScript1.By string literal2.By string object (using new keyword)

1) By string literalThe string literal is created using double quotes.

The syntax of creating string using string literal is given below:

var stringname="string value";example :<script>var str="This is string literal";document.write(str);</script>

Page 148: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

2) By string object (using new keyword)

The syntax of creating string object using new keyword is givenbelow:

var stringname=new String("string literal");Here, new keyword is used to create instance of string.example of creating string in JavaScript by new keyword.

<script>var stringname=new String("hello javascript string");document.write(stringname);</script>

Page 149: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

var name = new string("javascript string") ;

var lastname = new string("object") ;

var salary = new string('2303445') ;

document.write("name ="+name+"<br/>"+"lastname ="+lastname+

"<br/>"+"salary ="+salary);

Page 150: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

string lenght propertyThe length property contains an integer that indicates the number of characters in thestring object.

<html> <head> <title> create string object </title> </head><body><script>

var name = new string("sandeep kumar nehra") ;

document.write("number of character hold string object = "+name.length);</script>

</body></html>

Page 151: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

1) JavaScript String charAt(index) Method

The JavaScript String charAt() method returns the character at the given index.

<html>

<body>

<script>

var str="javascript";

document.write(str.charAt(3));

document.write(str.charAt(str.length-1));

</script>

</body>

</html>

Page 152: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

2. The substring() method extracts the characters in a stringbetween "start" and "end" position, not including “start & end" .

javascript string object substring method

<html><head> <title>substring method </title>

</head><body>

<script>var value ="this is khan , what you want this is not a matter";

var substring = value.substring(10,40);

document.write("first substring = "+substring);

document.write("<br/>"+"second substring = "+value.substring(30,60));

document.write("<br/>"+"third substring = "+value.substring(0,4));

</script> </body> </html>

Page 153: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

3. string uppercase and lowercase

a toUpperCase() method converts all the

alphabetic characters in a string to uppercase.

a toLowerCase() method converts all the

alphabetic characters in a string to lowercase.

the toUpperCase/toLowerCase method has no

effect on non-alphabetic characters.

Page 154: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

<html>

<head> <title> string object change case methods</title>

</head>

<body><script>

var name = new string("sandeep kumar nehra");

document.write("upper case____"+name.toUpperCase());

document.write('<br/>'+"lower case____"+name.toUpperCase().toLowerCase());

</script>

</body>

</html>

Page 155: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

4) JavaScript String concat(str) Method

The JavaScript String concat(str) method concatenates or joins two strings.

<html><body><script>var s1="javascript ";var s2="concat example";var s3=s1+s2;

document.write(s3);document.write('<br/>'+"this ".concat("is ").concat("free ").concat("offer"));

</script></body></html>

Page 156: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

5) the replace() method replaces a specified value with anothervalue in a string.

<html><body><script>var s1=“APS";var s2=“BEAS";var s = s2.replace(" BEAS ",“ASR");var s3=s1+s;

document.write(s3);

</script></body></html>

Page 157: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

6. The javascript string trim() removes the leading and trailingwhite space and line terminator characters from a string

<html><body><script>var s1 =" this is ram \n";

var l1 =s1.length;

document.write("before trim the string length = "+l1);

var s2 =s1.trim();var l2= s2.length;

document.write("<br>"+'after trim method call, the string length ='+l2);

</script></body></html>

Page 158: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

7. JavaScript String indexOf(str) MethodThe JavaScript String indexOf(str) method returns the index position of thegiven string.

the indexof() method returns the position of the first found occurrence of aspecified text inside a string.

note :this method returns -1 if the specified text is not found

<html><body><script>var s1="javascript from javatpoint indexof";var n=s1.indexOf("from");document.write(n);</script></body></html>

Page 159: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

8. the lastindexof() method returns the position of the lastfound occurrence of a specified value in a string

note :this method returns -1 if the specified text is not found

<html><body><script>var s1="javascript from javatpoint indexof";var n=s1.lastIndexOf("java");document.write(n);</script></body></html>

Page 160: JAVA SCRIPT are the statements that are always ignored by the interpreter. They are used to give remarks to the statement making it more readable and understandable to other programmers

9. JavaScript String slice(beginIndex, endIndex) Method

The JavaScript String slice(beginIndex, endIndex) methodreturns the parts of string from given beginIndex toendIndex. In slice() method, beginIndex is inclusive andendIndex is exclusive.

<script>var s1="abcdefgh";var s2=s1.slice(2,5);document.write(s2);</script>