SlideShare a Scribd company logo
JAVA SCRIPT
INTRODUCTION OF JAVA SCRIPT
 A scripting language is a lightweight programming
language.
 JavaScript is programming code that can be
inserted into HTML pages.
 JavaScript inserted into HTML pages, can be
executed by all modern web browsers.

 JavaScript is easy to learn.
HISTORY
 JavaScript was invented by Brendan Eich. It
appeared in Netscape (a no longer existing
browser) in 1995, and has been adopted by ECMA
(a standard association) since 1997.
SCRIPT TAG
 Scripts in HTML must be inserted between <script> and
</script> tags.
 Scripts can be put in the <body> and in the <head>
section of an HTML page.
The <script> Tag
 To insert a JavaScript into an HTML page, use the
<script> tag.
 The <script> and </script> tells where the JavaScript
starts and ends.
 The lines between the <script> and </script> contain the
JavaScript:
DEMO
 <script>
alert("My First JavaScript");
</script>
EVENT
 we want to execute code when an event occurs,
like when the user clicks a button.
FUNCTIONS
 if we put JavaScript code inside a function, we can
call that function when an event occurs.
JAVASCRIPT IN <HEAD> OR <BODY>
 You can place an unlimited number of scripts in an
HTML document.
 Scripts can be in the <body> or in the <head>
section of HTML, and/or in both.
 It is a common practice to put functions in the
<head> section, or at the bottom of the page. This
way they are all in one place and do not interfere
with page content.
EXTERNAL JAVASCRIPTS
 Scripts can also be placed in external files. External
files often contain code to be used by several
different web pages.
 External JavaScript files have the file extension .js.
 To use an external script, point to the .js file in the
"src" attribute of the <script> tag:
MANIPULATING HTML ELEMENTS
 To access an HTML element from JavaScript, you
can use the document.getElementById(id) method.
 Use the "id" attribute to identify the HTML element:
EXAMPLE
 <body>
<h1>My First Web Page</h1>
<p id="demo">My First Paragraph</p>
 <script>
document.getElementById("demo")
 .innerHTML="My First JavaScript";
</script>
WRITING TO THE DOCUMENT OUTPUT
 <h1>My First Web Page</h1>
<script>
document.write("<p>My First JavaScript
 </p>");
</script>
JAVASCRIPT STATEMENTS
 JavaScript statements are "commands" to the
browser. The purpose of the statements is to tell the
browser what to do.
 This JavaScript statement tells the browser to write
"Hello Dolly" inside an HTML element with
id="demo":
 document.getElementById("demo").innerHTML="H
ello Word";
SEMICOLON ;
 Semicolon separates JavaScript statements.
 Normally you add a semicolon at the end of each
executable statement.
 Using semicolons also makes it possible to write
many statements on one line.
JAVASCRIPT CODE
 JavaScript code (or just JavaScript) is a sequence
of JavaScript statements.
 Each statement is executed by the browser in the
sequence they are written.
 This example will manipulate two HTML elements:
JAVASCRIPT CODE BLOCKS
 JavaScript statements can be grouped together in
blocks.
 Blocks start with a left curly bracket, and end with a
right curly bracket.
 The purpose of a block is to make the sequence of
statements execute together.
 A good example of statements grouped together in
blocks, are JavaScript functions.
 This example will run a function that will manipulate
two HTML elements
JAVASCRIPT IS CASE SENSITIVE
 JavaScript is case sensitive.
 Watch your capitalization closely when you write
JavaScript statements:
 A function getElementById is not the same as
getElementbyID.
 A variable named myVariable is not the same as
MyVariable.
WHITE SPACE
 JavaScript ignores extra spaces. You can add white
space to your script to make it more readabl
 var name="Hege";
var name = "Hege“;
BREAK UP A CODE LINE
 document.write("Hello 
World!");
JAVASCRIPT COMMENTS
 // Write to a heading:
document.getElementById("myH1").innerHTML="W
elcome to my Homepage";
 /*
The code below will write
to a heading and to a paragraph,
and will represent the start of
my homepage:
*/
COMMENT CONT…
 var x=5; // declare x and assign 5 to it
var y=x+2; // declare y and assign x+2 to it
JAVASCRIPT VARIABLES
 Variable names must begin with a letter
 Variable names can also begin with $ and _ (but we
will not use it)
 Variable names are case sensitive (y and Y are
different variables)
JAVASCRIPT DATA TYPES
 JavaScript variables can also hold other types of data,
like text values (name="John Doe").
 In JavaScript a text like "John Doe" is called a string.
 There are many types of JavaScript variables, but for
now, just think of numbers and strings.
 When you assign a text value to a variable, put double or
single quotes around the value.
 When you assign a numeric value to a variable, do not
put quotes around the value. If you put quotes around a
numeric value, it will be treated as text.
DATA TYPE EXAMPLES
 var pi=3.14;
var name="John Doe";
var answer='Yes I am!';
DECLARING JAVASCRIPT VARIABLES
 You declare JavaScript variables with the var
keyword
 var carname;
 carname = “Volvo”;
 var carname = “volvo”;
JAVASCRIPT IS LOOSELY TYPED
 JavaScript is weakly typed. This means that the
same variable can be used as different types:
 Example
 var x // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
JAVASCRIPT ARRAYS
 var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
JAVASCRIPT OBJECTS
 var person={ firstname:"John",
 lastname:“Dolly", id:5566 };
 You can address the object properties in two ways:
 name=person.lastname;
name=person["lastname"];
DECLARING VARIABLE TYPES
 When you declare a new variable, you can declare
its type using the "new" keyword:
 var carname = new String;
var x = new Number;
var y = new Boolean;
var cars = new Array;
var person = new Object; a
JAVA SCRIPT OBJECT
 "Everything" in JavaScript is an Object: a String, a
Number, an Array, a Date....
 In JavaScript, an object is data, with properties and
methods.
PROPERTIES AND METHODS
 Properties are values associated with an object.
 Methods are actions that can be performed on
objects.
A REAL LIFE OBJECT. A CAR:
FUNCTION IN JAVA SCRIPT
 General Syntax
 function function_name([list of parameters])
{
some code to be executed
}
NO PARAMETER NO RETURN VALUE
 <script>
function myFunction()
{
alert("Hello World!");
}
</script>
NO PARAMETER WITH RETURN VALUE
 <script>
function pi()
{
return 3.14
 }
</script>
WITH PARAMETER NO RETURN
 <script>
function myFunction(val1,val2)
{
alert(“sum of two value is “ + (val1+val2));
}
</script>
WITH PARAMETER WITH RETURN
 <script>
function myFunction(val1,val2)
{
return (val1+val2);
}
</script>
LOCAL JAVASCRIPT VARIABLES
 A variable declared (using var) within a JavaScript
function becomes LOCAL and can only be
accessed from within that function. (the variable
has local scope).
 You can have local variables with the same name in
different functions, because local variables are only
recognized by the function in which they are
declared.
 Local variables are deleted as soon as the function
is completed.
GLOBAL JAVASCRIPT VARIABLES
 Variables declared outside a function, become
GLOBAL, and all scripts and functions on the web
page can access it.
THE LIFETIME OF JAVASCRIPT VARIABLES
 The lifetime JavaScript variables starts when they
are declared.
 Local variables are deleted when the function is
completed.
 Global variables are deleted when you close the
page.
ASSIGNING VALUES TO UNDECLARED
JAVASCRIPT VARIABLES
 If you assign a value to variable that has not yet
been declared, the variable will automatically be
declared as a GLOBAL variable.
JAVASCRIPT OPERATORS
 = is used to assign values.
 The assignment operator = is used to assign values
to JavaScript variables.
 + is used to add values.
 The arithmetic operator + is used to add values
together.
ARITHMETIC OPERATOR
 Operator example x y
 + Addition x=y+2 7 5
 - Subtraction x=y-2 3 5
 * Multiplication x=y*2 10 5
 / Division x=y/2 2.5 5
 % Modulus x=y%2 1 5
 ++ Increment x=++y 6 6
x=y++ 5 6
-- Decrement x=--y 4 4
x=y-- 5 4
THE + OPERATOR USED ON STRINGS
 txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
ADDING STRINGS AND NUMBERS
 x=5+5;
y="5"+5;
z="Hello"+5;
 output
 10
55
Hello5
COMPRESSION OPERATOR
 == is equal to
 === is exactly equal to (value and type)
 != is not equal
 !== is not equal (neither value nor type)
 > is greater than
 < is less than
 >= is greater than or equal to
 <= is less than or equal to
LOGICAL OPERATORS
 && and (x < 10 && y > 1)
 || or (x==5 || y==5)
 ! not !(x==y)
 Consider x = 6 and y = 3
CONDITIONAL OPERATOR
 JavaScript also contains a conditional operator that
assigns a value to a variable based on some
condition.
 Syntax
 Variable name=(condition)?value1:value2
 Example
voteable=(age<18)?"Too young":"Old enough";
CONDITIONAL STATEMENTS
 Very often when you write code, you want to
perform different actions for different decisions. You
can use conditional statements in your code to do
this.
CONDITIONAL STATEMENTS CONT..
 In JavaScript we have the following conditional
statements:
 if statement - use this statement to execute some code
only if a specified condition is true
 if...else statement - use this statement to execute some
code if the condition is true and another code if the
condition is false
 if...else if....else statement - use this statement to select
one of many blocks of code to be executed
 switch statement - use this statement to select one of
many blocks of code to be executed
IF STATEMENT
 if (condition)
{
code to be executed if condition is true
}
IF…ELSE
 if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
IF … ELSE IF … ELSE
 if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor
condition2 is true
}
THE JAVASCRIPT SWITCH STATEMENT
 switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1
and 2
}
JAVASCRIPT LOOPS
 Loops are handy, if you want to run the same code
over and over again, each time with a different
value.
PROBLEM
 document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
document.write(cars[6] + "<br>");
document.write(cars[7] + "<br>");
document.write(cars[8] + "<br>");
document.write(cars[9] + "<br>");
document.write(cars[10] + "<br>");
SOLUTION
 for (var i=0;i<=10;i++)
{
document.write(cars[i] + "<br>");
}
THE FOR LOOP
 for (variable initialization ; Condition Checking ;
increment or decrement )
{
the code block to be executed
}
THE WHILE LOOP
 while (condition)
{
code block to be executed
}
THE DO WHILE LOOP
 do
{
code block to be executed
}
while (condition);
JAVASCRIPT BREAK AND CONTINUE
 The Break Statement
 You have already seen the break statement used in an
earlier chapter of this tutorial. It was used to "jump out" of
a switch() statement.
 The break statement can also be used to jump out of a
loop.
 The break statement breaks the loop and continues
executing the code after the loop (if any):
EXAMPLE
 for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br>";
}
THE CONTINUE STATEMENT
 The continue statement breaks one iteration (in
the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
EXAMPLE
 for (i=0;i<=10;i++)
{
if (i==3) continue;
x=x + "The number is " + i + "<br>";
}
JAVA SCRIPT LABELS
 break labelname;
continue labelname;
JAVA SCRIPT LABELS EXAMPLE
 cars=["BMW","Volvo","Saab","Ford"];
list:
{
document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
break list;
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
}
JAVA SCRIPT ERROR HANDLING
 The try statement lets you to test a block of code
for errors.
 The catch statement lets you handle the error.
 The throw statement lets you create custom errors.
ERRORS WILL HAPPEN!
 When the JavaScript engine is executing
JavaScript code, different errors can occur:
 It can be syntax errors, typically coding errors or
typos made by the programmer.
 It can be misspelled or missing features in the
language (maybe due to browser differences).
 It can be errors due to wrong input, from a user, or
from an Internet server.
 And, of course, it can be many other unforeseeable
things.
JAVASCRIPT THROWS ERRORS
 When an error occurs, when something goes
wrong, the JavaScript engine will normally stop,
and generate an error message.
 The technical term for this is: JavaScript will throw
an error.
JAVASCRIPT TRY AND CATCH
 The try statement allows you to define a block of
code to be tested for errors while it is being
executed.
 The catch statement allows you to define a block of
code to be executed, if an error occurs in the try
block.
 The JavaScript statements try and catch come in
pairs.
SYNTAX
 try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}
EXAMPLE
 <script>
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.nn";
txt+="Error description: " + err.message + "nn";
txt+="Click OK to continue.nn";
alert(txt);
}
}
</script>

<input type="button" value="View message" onclick="message()">
THE THROW STATEMENT
 The throw statement allows you to create a custom
error.
 The correct technical term is to create or throw an
exception.
 If you use the throw statement together with try and
catch, you can control program flow and generate
custom error messages.
EXAMPLE
 script>
function myFunction()
{
try
{
var x=document.getElementById("demo").value;
if(x=="") throw "empty";
if(isNaN(x)) throw "not a number";
if(x>10) throw "to high";
if(x<5) throw "too low";
}
catch(err)
{
var y=document.getElementById("mess");
y.innerHTML="Error: " + err + ".";}
}
}
</script>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="mess"></p>
JAVASCRIPT FORM VALIDATION
 JavaScript can be used to validate data in HTML forms
before sending off the content to a server.
 Form data that typically are checked by a JavaScript
could be:
 has the user left required fields empty?
 has the user entered a valid e-mail address?
 has the user entered a valid date?
 has the user entered text in a numeric field?
NULL FIELDS
 function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
E-MAIL VALIDATION
 function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 ||
dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
THE HTML DOM (DOCUMENT OBJECT
MODEL)
 When a web page is loaded, the browser creates a
Document Object Model of the page.
DOM MODEL
Window
Document
Forms
Forms
Elements
Elements
WITH THE DOM
 With a programmable object model, JavaScript gets
all the power it needs to
 create dynamic HTML:
 JavaScript can change all the HTML elements in
the page
 JavaScript can change all the HTML attributes in
the page
 JavaScript can change all the CSS styles in the
page
 JavaScript can react to all the events in the page
FINDING HTML ELEMENTS
 Often, with JavaScript, you want to manipulate
HTML elements.
 To do so, you have to find the elements first. There
are a couple of ways to do this:
 Finding HTML elements by id
 Finding HTML elements by tag name
 Finding HTML elements by class name
FINDING HTML ELEMENTS BY ID
 var x=document.getElementById("intro");
FINDING HTML ELEMENTS BY TAG NAME
 var x=document.getElementById("main");
var y=x.getElementsByTagName("p");
CHANGING THE HTML OUTPUT STREAM
 <body>
<script>
document.write(Date());
</script>
</body>
CHANGING HTML CONTENT
 The easiest way to modify the content of an HTML
element is by using the innerHTML property.
 To change the content of an HTML element, use
this syntax:
 document.getElementById(id).innerHTML=
 new HTML
EXAMPLE
 <p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New
text!";
</script>
CHANGING AN HTML ATTRIBUTE
 To change the attribute of an HTML element, use
this syntax:
 document.getElementById(id).attribute=new value
EXAMPLE
 <img id="image" src="smiley.gif">
<script>
document.getElementById("image").src="landscape
.jpg";
</script>
EVENTS
 A JavaScript can be executed when an event
occurs, like when a user clicks on an HTML
element.
 To execute code when a user clicks on an element,
add JavaScript code to an HTML event attribute:
 Example :
 onclick=JavaScript
 When a user clicks the mouse
 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted
 When a user strokes a key
ONCLICK
 <button onclick="displayDate()">Try it</button>
THE ONLOAD AND ONUNLOAD EVENTS
 he onload and onunload events are triggered when
the user enters or leaves the page.
 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.
EXAMPLE
 <body onload=“viewdate()">
 <script>
 Function viewdate()
 {
 alert(date());
 }
 </script>
ON MOUSE OVER
 The onmouseover and onmouseout events can be
used to trigger a function when the user mouses
over, or out of, an HTML element.
EXAMPLE
 <div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-
color:#D94A38;width:120px;height:20px;padding:40px;">Mouse
Over Me</div>
 <script>
 function mOver(obj)
 {
 obj.innerHTML="Thank You"
 }
 function mOut(obj)
 {
 obj.innerHTML="Mouse Over Me"
 }
 </script>
THE ONMOUSEDOWN, ONMOUSEUP AND
ONCLICK EVENTS
 The onmousedown, onmouseup, and onclick
events are all parts of a mouse-click. First when a
mouse-button is clicked, the onmousedown event is
triggered, then, when the mouse-button is released,
the onmouseup event is triggered, finally, when the
mouse-click is completed, the onclick event is
triggered.
EXAMPLE
 <div onmousedown="mDown(this)" onmouseup="mUp(this)"
style="background-
color:#D94A38;width:90px;height:20px;padding:40px;">Click Me</div>
 <script>
 function mDown(obj)
 {
 obj.style.backgroundColor="#1ec5e5";
 obj.innerHTML="Release Me"
 }
 function mUp(obj)
 {
 obj.style.backgroundColor="#D94A38";
 obj.innerHTML="Thank You"
 }
 </script>
CREATING NEW HTML ELEMENTS
 To add a new element to the HTML DOM, you must
create the element (element node) first, and then
append it to an existing element.
EXAMPLE
 <div id="d1">
 <p id="p1">This is a paragraph.</p>
 <p id="p2">This is another paragraph.</p>
 </div>
 <script>
 var para=document.createElement("p");
 var node=document.createTextNode("This is new.");
 para.appendChild(node);
 var element=document.getElementById("d1");
 element.appendChild(para);
 </script>
REMOVING EXISTING HTML ELEMENTS
 To remove an HTML element, you must know the
parent of the element:
EXAMPLE
 <div id="d1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div><script>
var parent=document.getElementById("d1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>
THE JAVA SCRIPT OBJECT
 JavaScript has several built-in objects, like String,
Date, Array, and more.
 An object is just a special kind of data, with
properties and methods
CREATING JAVASCRIPT OBJECTS
 With JavaScript you can define and create your
own objects.
 There are 2 different ways to create a new object:
 1. Define and create a direct instance of an object.
 2. Use a function to define an object, then create
new object instances.
CREATING A DIRECT INSTANCE
 person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
USING AN OBJECT CONSTRUCTOR
 function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
 var myFather=new person("John","Doe",50,"blue");
var myMother=new person("Sally","Rally",48,"green");
ADDING METHODS TO JAVASCRIPT OBJECTS
 function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.changeName=changeName;
 function changeName(name)
{
this.lastname=name;
}
}
JAVASCRIPT CLASSES
 JavaScript is an object oriented language, but
JavaScript does not use classes.
 In JavaScript you don’t define classes and create
objects from these classes (as in most other object
oriented languages).
 JavaScript is prototype based, not class based.
JAVASCRIPT FOR...IN LOOP
 The JavaScript for...in statement loops through the
properties of an object.
 Syntax
 for (variable in object)
{
code to be executed
}
EXAMPLE
 var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
txt=txt + person[x];
}
JAVASCRIPT NUMBERS
 var pi=3.14; // Written with decimals
var x=34; // Written without decimals
 All JavaScript Numbers are 64-bit
 JavaScript is not a typed language. Unlike many
other programming languages, it does not define
different types of numbers, like integers, short, long,
floating-point etc.
JAVASCRIPT STRINGS
 A string simply stores a series of characters like
"John Doe".
 A string can be any text inside quotes. You can use
simple or double quotes:
 var carname="Volvo XC60";
var carname='Volvo XC60';
 You can access each character in a string with its
position (index):
 Example
 var character=carname[7];
STRING METHODS
 charAt() charCodeAt()
 concat() fromCharCode()
 indexOf() lastIndexOf()
 match() replace()
 search() slice()
 split() substr()
 substring() toLowerCase()
 toUpperCase() valueOf()
DATE OBJECT
 Date()
 Returns current date and time
 getFullYear()
Use getFullYear() to get the year.
 getTime()
getTime() returns the number of milliseconds since
01.01.1970.
SET A DATE
 var myDate=new Date();
myDate.setFullYear(2010,0,14);
 And also
 var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
COMPARE TWO DATES
 var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();
if (x>today)
{
alert("Today is before 14th January 2100");
}
else
{
alert("Today is after 14th January 2100");
}
ARRAY
 An array is a special variable, which can hold more than
one value at a time.
 If you have a list of items (a list of car names, for
example), storing the cars in single variables could look
like this:
 var car1="Saab";
var car2="Volvo";
var car3="BMW";
 However, what if you want to loop through the cars and
find a specific one? And what if you had not 3 cars, but
300?
 The solution is an array!
YOU CAN HAVE DIFFERENT OBJECTS IN ONE
ARRAY
 myArray[0]=Date.now;
myArray[1]=myFunction;
myArray[2]=myCars;
CREATING ARRAY
 1: Regular:
 var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
 2: Condensed:
 var myCars=new Array("Saab","Volvo","BMW");
 3: Literal:
 var myCars=["Saab","Volvo","BMW"];
ARRAY METHODS AND PROPERTIES
 Property
length
 Methods
 indexOf() concat()
 Join() pop()
 push() reverse()
 shift() slice()
 sort() splice()
 toString() unshift()
BOOLEAN
 There is only Two states
 True
 False
MATH FUNCTIONS
 abs() ceil()
 exp() floor()
 max() min()
 pow() random()
 round() sqrt()
REGULAR EXPRESSION
 A regular expression is an object that describes a pattern
of characters.
 When you search in a text, you can use a pattern to
describe what you are searching for.
 A simple pattern can be one single character.
 A more complicated pattern can consist of more
characters, and can be used for parsing, format
checking, substitution and more.
 Regular expressions are used to perform powerful
pattern-matching and "search-and-replace" functions on
text.
SYNTAX
 var patt=new RegExp(pattern,modifiers);
or more simply:
var patt=/pattern/modifiers;
 pattern specifies the pattern of an expression
 modifiers specify if a search should be global, case-
sensitive, etc.
MODIFIERS
 Modifiers are used to perform case-insensitive and
global searches.
 The i modifier is used to perform case-insensitive
matching.
 The g modifier is used to perform a global match
(find all matches rather than stopping after the first
match).
EXAMPLE
 <script>
 var str = "Visit W3Schools";
 var patt1 = /w3schools/i;
 document.write(str.match(patt1));
 </script>
EXAMPLE 2
 <script>
 var str="Is this all there is?";
 var patt1=/is/g;
 document.write(str.match(patt1));
 </script>
EXAMPLE
 <script>
 var str="Is this all there is?";
 var patt1=/is/gi;
 document.write(str.match(patt1));
 </script>
TEST()
 The test() method searches a string for a specified
value, and returns true or false, depending on the
result.
EXAMPLE
 <script>
 var patt1=new RegExp("e");
 document.write(patt1.test("The best things in life
are free"));
 </script>
 </body>
EXEC()
 The exec() method searches a string for a specified
value, and returns the text of the found value. If no
match is found, it returns null.
EXAMPLE
 <script>
 var patt1=new RegExp("e");
 document.write(patt1.exec("The best things in life
are free"));
 </script>
JAVA SCRIPT OBJECTS
 Window Object
 Screen Object
 History Object
 Navigator Object
 Popupalert Object
 Timing Object
 Cookie Object
WINDOW OBJECT
 The window object is supported by all browsers. It
represent the browsers window.
 All global JavaScript objects, functions, and variables
automatically become members of the window object.
 Global variables are properties of the window object.
 Global functions are methods of the window object.
 Even the document object (of the HTML DOM) is a
property of the window object:
WINDOW SIZE
 Three different properties can be used to determine the size of
the browser window (the browser viewport, NOT including
toolbars and scrollbars).
 For Internet Explorer, Chrome, Firefox, Opera, and Safari:
 window.innerHeight - the inner height of the browser window
 window.innerWidth - the inner width of the browser window
 For Internet Explorer 8, 7, 6, 5:
 document.documentElement.clientHeight
 document.documentElement.clientWidth
OTHER WINDOW METHODS
 window.open() - open a new window
 window.close() - close the current window
 window.moveTo() -move the current window
 window.resizeTo() -resize the current window
WINDOW SCREEN OBJECT
 The window.screen object can be written without
the window prefix.
 document.write("Available Width: " +
screen.availWidth);
document.write("Available Height: " +
screen.availHeight);
EXAMPLE
 <h3>Your Screen:</h3>
 <script>
 document.write("Total width/height: ");
 document.write(screen.width + "*" + screen.height);
 document.write("<br>");
 document.write("Available width/height: ");
 document.write(screen.availWidth + "*" + screen.availHeight);
 document.write("<br>");
 document.write("Color depth: ");
 document.write(screen.colorDepth);
 document.write("<br>");
 document.write("Color resolution: ");
 document.write(screen.pixelDepth);
 </script>
LOCATION OBJECT
 The window.location object can be used to get the
current page address (URL) and to redirect the
browser to a new page.
 location.hostname returns the domain name of the
web host
 location.path returns the path and filename of the
current page
 location.port returns the port of the web host (80 or
443)
 location protocol returns the web protocol used
(http:// or https://)
EXAMPLE
 document.write(location.href);
 document.write(location.pathname);
 function newDoc()
{
window.location.assign("http://www.
w3schools.com");
}
HISTORY OBJECT
 To protect the privacy of the users, there are
limitations to how JavaScript can access this obje
 history.back() - same as clicking back in the
browser
 history.forward() - same as clicking forward in the
browser
EXAMPLE
 <script>
function goBack()
{
window.history.back()
}
</script>
<input type="button" value="Back"
onclick="goBack()">
EXAMPLE
 <script>
function goForward()
{
window.history.forward()
}
</script>
<input type="button" value="Forward"
onclick="goForward()">
NAVIGATOR OBJECT
 <script>
navigator.appCodeName
navigator.appName
navigator.appVersion
navigator.cookieEnabled
navigator.platform
navigator.userAgent
navigator.systemLanguage
WARNING !!!
 The information from the navigator object can often
be misleading, and should not be used to detect
browser versions because:
 The navigator data can be changed by the browser
owner
 Some browsers misidentify themselves to bypass
site tests
 Browsers cannot report new operating systems,
released later than the browser
POPUP BOXES
 JavaScript has three kind of popup boxes: Alert
box, Confirm box, and Prompt box.
ALERT BOX
 An alert box is often used if you want to make sure
information comes through to the user.
 When an alert box pops up, the user will have to
click "OK" to proceed.
 Syntax
 window.alert("sometext");
EXAMPLE
 <head>
<script>
function myFunction()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="myFunction()"
value="Show alert box">
</body>
CONFIRM BOX
 A confirm box is often used if you want the user to
verify or accept something.
 When a confirm box pops up, the user will have to
click either "OK" or "Cancel" to proceed.
 If the user clicks "OK", the box returns true. If the
user clicks "Cancel", the box returns false
 Syntax
 window.confirm("sometext");
EXAMPLE
 var r=confirm("Press a button");
if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}
PROMPT BOX
 A prompt box is often used if you want the user to
input a value before entering a page.
 When a prompt box pops up, the user will have to
click either "OK" or "Cancel" to proceed after
entering an input value.
 If the user clicks "OK" the box returns the input
value. If the user clicks "Cancel" the box returns
null.
 Syntax
 window.prompt("sometext","defaultvalue");
EXAMPLE
 var name=prompt("Please enter your name","Harry
Potter");
 if (name!=null && name!="")
{
x="Hello " + name + "! How are you today?";
}
LINE BREAKS
 To display line breaks inside a popup box, use a
back-slash followed by the character n.
 Example
 alert("Hellon How are you?");
JAVASCRIPT TIMING EVENTS
 With JavaScript, it is possible to execute some
code at specified time-intervals. This is called
timing events.
 It's very easy to time events in JavaScript. The two
key methods that are used are:
 setInterval() - executes a function, over and over
again, at specified time intervals
 setTimeout() - executes a function, once, after
waiting a specified number of milliseconds
SETINTERVAL()
 The setInterval() Method
 The setInterval() method will wait a specified
number of milliseconds, and then execute a
specified function, and it will continue to execute
the function, once at every given time-interval.
 Syntax
 window.setInterval("javascript
function",milliseconds);
EXAMPLE
 1) setInterval(function(){alert("Hello")},3000);
 2)
 var myVar= setInterval(function() {myTimer()},
 1000);
function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo")
 . innerHTML=t;
}
HOW TO STOP THE EXECUTION?
 The clearInterval() method is used to stop further
executions of the function specified in the
setInterval() method.
 Syntax
 window.clearInterval(intervalVariable)
SETTIMEOUT()
 indow.setTimeout("javascript
function",milliseconds);
 Example
 setTimeout(function(){alert("Hello")},3000);
HOW TO STOP THE EXECUTION?
 The clearTimeout() method is used to stop the
execution of the function specified in the
setTimeout() method.
 Syntax
 window.clearTimeout(timeoutVariable)
COOKIES
 A cookie is a variable that is stored on the visitor's
computer. Each time the same computer requests a
page with a browser, it will send the cookie too.
With JavaScript, you can both create and retrieve
cookie values.

More Related Content

PDF
Javascript basics
PPTX
Java script
PPTX
Lab #2: Introduction to Javascript
PPT
Java Script ppt
PPT
Introduction to Javascript
PDF
3. Java Script
PPT
Javascript
PPT
JavaScript - An Introduction
Javascript basics
Java script
Lab #2: Introduction to Javascript
Java Script ppt
Introduction to Javascript
3. Java Script
Javascript
JavaScript - An Introduction

What's hot (20)

PPT
Js ppt
PDF
Basics of JavaScript
PDF
JavaScript - Chapter 12 - Document Object Model
PPT
Javascript
PDF
Javascript essentials
PPTX
Javascript
PPT
Introduction to JavaScript
PPTX
Dom(document object model)
PPT
Jsp ppt
PPT
JavaScript & Dom Manipulation
PPTX
Java script
PDF
JavaScript Programming
PPTX
Event In JavaScript
PDF
JavaScript - Chapter 11 - Events
PPTX
Javascript 101
PPTX
Javascript event handler
PPSX
Javascript variables and datatypes
PDF
JavaScript - Chapter 6 - Basic Functions
PPTX
Id and class selector
PDF
JavaScript - Chapter 14 - Form Handling
Js ppt
Basics of JavaScript
JavaScript - Chapter 12 - Document Object Model
Javascript
Javascript essentials
Javascript
Introduction to JavaScript
Dom(document object model)
Jsp ppt
JavaScript & Dom Manipulation
Java script
JavaScript Programming
Event In JavaScript
JavaScript - Chapter 11 - Events
Javascript 101
Javascript event handler
Javascript variables and datatypes
JavaScript - Chapter 6 - Basic Functions
Id and class selector
JavaScript - Chapter 14 - Form Handling
Ad

Viewers also liked (20)

PPT
Java script final presentation
PPT
Java script
PPTX
An Overview of HTML, CSS & Java Script
PDF
8 introduction to_java_script
PPT
Java script
PPT
A quick guide to Css and java script
PPTX
Java script
PDF
Introduction to JavaScript
PPT
Javascript
PPTX
HTML, CSS and Java Scripts Basics
KEY
HTML presentation for beginners
PPT
Html Ppt
PPTX
BluePrint CSS slides for OSS Bar Camp Dublin
KEY
Introduction to javascript
PPT
Java Script Introduction
PPT
1 introduction to xml
PPT
AK css
PDF
DOC
Spring.pdf
PDF
C++ L02-Conversion+enum+Operators
Java script final presentation
Java script
An Overview of HTML, CSS & Java Script
8 introduction to_java_script
Java script
A quick guide to Css and java script
Java script
Introduction to JavaScript
Javascript
HTML, CSS and Java Scripts Basics
HTML presentation for beginners
Html Ppt
BluePrint CSS slides for OSS Bar Camp Dublin
Introduction to javascript
Java Script Introduction
1 introduction to xml
AK css
Spring.pdf
C++ L02-Conversion+enum+Operators
Ad

Similar to Java script (20)

PPTX
Web programming
PPTX
Unit - 4 all script are here Javascript.pptx
PDF
JAVA SCRIPT
PPTX
04-JS.pptx
PPTX
04-JS.pptx
PPTX
04-JS.pptx
PPT
UNIT 3.ppt
PDF
Javascript tutorial basic for starter
PPTX
Javascript Tlabs
PPTX
Lecture 5 javascript
PDF
javascriptPresentation.pdf
PPTX
JavaScript_III.pptx
PPTX
JavaScript Fundamentals & JQuery
PPTX
Basics of Javascript
PDF
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
PDF
Ch3- Java Script.pdf
PPTX
Java script.pptx v
RTF
Java scripts
PPTX
Chapter 3 INTRODUCTION TO JAVASCRIPT S.pptx
PPTX
Unit III.pptx IT3401 web essentials presentatio
Web programming
Unit - 4 all script are here Javascript.pptx
JAVA SCRIPT
04-JS.pptx
04-JS.pptx
04-JS.pptx
UNIT 3.ppt
Javascript tutorial basic for starter
Javascript Tlabs
Lecture 5 javascript
javascriptPresentation.pdf
JavaScript_III.pptx
JavaScript Fundamentals & JQuery
Basics of Javascript
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
Ch3- Java Script.pdf
Java script.pptx v
Java scripts
Chapter 3 INTRODUCTION TO JAVASCRIPT S.pptx
Unit III.pptx IT3401 web essentials presentatio

More from Shyam Khant (8)

PPT
Unit2.data type, operators, control structures
PPT
Introducing to core java
PDF
PPTX
PPTX
C++ theory
PPTX
C Theory
PPTX
PPTX
Hashing 1
Unit2.data type, operators, control structures
Introducing to core java
C++ theory
C Theory
Hashing 1

Recently uploaded (20)

PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
master seminar digital applications in india
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Cell Structure & Organelles in detailed.
PPTX
Cell Types and Its function , kingdom of life
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Presentation on HIE in infants and its manifestations
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
A systematic review of self-coping strategies used by university students to ...
Microbial diseases, their pathogenesis and prophylaxis
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
master seminar digital applications in india
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Microbial disease of the cardiovascular and lymphatic systems
O5-L3 Freight Transport Ops (International) V1.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Cell Structure & Organelles in detailed.
Cell Types and Its function , kingdom of life
Final Presentation General Medicine 03-08-2024.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Chinmaya Tiranga quiz Grand Finale.pdf
RMMM.pdf make it easy to upload and study
VCE English Exam - Section C Student Revision Booklet
Presentation on HIE in infants and its manifestations
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3

Java script

  • 2. INTRODUCTION OF JAVA SCRIPT  A scripting language is a lightweight programming language.  JavaScript is programming code that can be inserted into HTML pages.  JavaScript inserted into HTML pages, can be executed by all modern web browsers.   JavaScript is easy to learn.
  • 3. HISTORY  JavaScript was invented by Brendan Eich. It appeared in Netscape (a no longer existing browser) in 1995, and has been adopted by ECMA (a standard association) since 1997.
  • 4. SCRIPT TAG  Scripts in HTML must be inserted between <script> and </script> tags.  Scripts can be put in the <body> and in the <head> section of an HTML page. The <script> Tag  To insert a JavaScript into an HTML page, use the <script> tag.  The <script> and </script> tells where the JavaScript starts and ends.  The lines between the <script> and </script> contain the JavaScript:
  • 5. DEMO  <script> alert("My First JavaScript"); </script>
  • 6. EVENT  we want to execute code when an event occurs, like when the user clicks a button.
  • 7. FUNCTIONS  if we put JavaScript code inside a function, we can call that function when an event occurs.
  • 8. JAVASCRIPT IN <HEAD> OR <BODY>  You can place an unlimited number of scripts in an HTML document.  Scripts can be in the <body> or in the <head> section of HTML, and/or in both.  It is a common practice to put functions in the <head> section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.
  • 9. EXTERNAL JAVASCRIPTS  Scripts can also be placed in external files. External files often contain code to be used by several different web pages.  External JavaScript files have the file extension .js.  To use an external script, point to the .js file in the "src" attribute of the <script> tag:
  • 10. MANIPULATING HTML ELEMENTS  To access an HTML element from JavaScript, you can use the document.getElementById(id) method.  Use the "id" attribute to identify the HTML element:
  • 11. EXAMPLE  <body> <h1>My First Web Page</h1> <p id="demo">My First Paragraph</p>  <script> document.getElementById("demo")  .innerHTML="My First JavaScript"; </script>
  • 12. WRITING TO THE DOCUMENT OUTPUT  <h1>My First Web Page</h1> <script> document.write("<p>My First JavaScript  </p>"); </script>
  • 13. JAVASCRIPT STATEMENTS  JavaScript statements are "commands" to the browser. The purpose of the statements is to tell the browser what to do.  This JavaScript statement tells the browser to write "Hello Dolly" inside an HTML element with id="demo":  document.getElementById("demo").innerHTML="H ello Word";
  • 14. SEMICOLON ;  Semicolon separates JavaScript statements.  Normally you add a semicolon at the end of each executable statement.  Using semicolons also makes it possible to write many statements on one line.
  • 15. JAVASCRIPT CODE  JavaScript code (or just JavaScript) is a sequence of JavaScript statements.  Each statement is executed by the browser in the sequence they are written.  This example will manipulate two HTML elements:
  • 16. JAVASCRIPT CODE BLOCKS  JavaScript statements can be grouped together in blocks.  Blocks start with a left curly bracket, and end with a right curly bracket.  The purpose of a block is to make the sequence of statements execute together.  A good example of statements grouped together in blocks, are JavaScript functions.  This example will run a function that will manipulate two HTML elements
  • 17. JAVASCRIPT IS CASE SENSITIVE  JavaScript is case sensitive.  Watch your capitalization closely when you write JavaScript statements:  A function getElementById is not the same as getElementbyID.  A variable named myVariable is not the same as MyVariable.
  • 18. WHITE SPACE  JavaScript ignores extra spaces. You can add white space to your script to make it more readabl  var name="Hege"; var name = "Hege“;
  • 19. BREAK UP A CODE LINE  document.write("Hello World!");
  • 20. JAVASCRIPT COMMENTS  // Write to a heading: document.getElementById("myH1").innerHTML="W elcome to my Homepage";  /* The code below will write to a heading and to a paragraph, and will represent the start of my homepage: */
  • 21. COMMENT CONT…  var x=5; // declare x and assign 5 to it var y=x+2; // declare y and assign x+2 to it
  • 22. JAVASCRIPT VARIABLES  Variable names must begin with a letter  Variable names can also begin with $ and _ (but we will not use it)  Variable names are case sensitive (y and Y are different variables)
  • 23. JAVASCRIPT DATA TYPES  JavaScript variables can also hold other types of data, like text values (name="John Doe").  In JavaScript a text like "John Doe" is called a string.  There are many types of JavaScript variables, but for now, just think of numbers and strings.  When you assign a text value to a variable, put double or single quotes around the value.  When you assign a numeric value to a variable, do not put quotes around the value. If you put quotes around a numeric value, it will be treated as text.
  • 24. DATA TYPE EXAMPLES  var pi=3.14; var name="John Doe"; var answer='Yes I am!';
  • 25. DECLARING JAVASCRIPT VARIABLES  You declare JavaScript variables with the var keyword  var carname;  carname = “Volvo”;  var carname = “volvo”;
  • 26. JAVASCRIPT IS LOOSELY TYPED  JavaScript is weakly typed. This means that the same variable can be used as different types:  Example  var x // Now x is undefined var x = 5; // Now x is a Number var x = "John"; // Now x is a String
  • 27. JAVASCRIPT ARRAYS  var cars=new Array(); cars[0]="Saab"; cars[1]="Volvo"; cars[2]="BMW";
  • 28. JAVASCRIPT OBJECTS  var person={ firstname:"John",  lastname:“Dolly", id:5566 };  You can address the object properties in two ways:  name=person.lastname; name=person["lastname"];
  • 29. DECLARING VARIABLE TYPES  When you declare a new variable, you can declare its type using the "new" keyword:  var carname = new String; var x = new Number; var y = new Boolean; var cars = new Array; var person = new Object; a
  • 30. JAVA SCRIPT OBJECT  "Everything" in JavaScript is an Object: a String, a Number, an Array, a Date....  In JavaScript, an object is data, with properties and methods.
  • 31. PROPERTIES AND METHODS  Properties are values associated with an object.  Methods are actions that can be performed on objects.
  • 32. A REAL LIFE OBJECT. A CAR:
  • 33. FUNCTION IN JAVA SCRIPT  General Syntax  function function_name([list of parameters]) { some code to be executed }
  • 34. NO PARAMETER NO RETURN VALUE  <script> function myFunction() { alert("Hello World!"); } </script>
  • 35. NO PARAMETER WITH RETURN VALUE  <script> function pi() { return 3.14  } </script>
  • 36. WITH PARAMETER NO RETURN  <script> function myFunction(val1,val2) { alert(“sum of two value is “ + (val1+val2)); } </script>
  • 37. WITH PARAMETER WITH RETURN  <script> function myFunction(val1,val2) { return (val1+val2); } </script>
  • 38. LOCAL JAVASCRIPT VARIABLES  A variable declared (using var) within a JavaScript function becomes LOCAL and can only be accessed from within that function. (the variable has local scope).  You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.  Local variables are deleted as soon as the function is completed.
  • 39. GLOBAL JAVASCRIPT VARIABLES  Variables declared outside a function, become GLOBAL, and all scripts and functions on the web page can access it.
  • 40. THE LIFETIME OF JAVASCRIPT VARIABLES  The lifetime JavaScript variables starts when they are declared.  Local variables are deleted when the function is completed.  Global variables are deleted when you close the page.
  • 41. ASSIGNING VALUES TO UNDECLARED JAVASCRIPT VARIABLES  If you assign a value to variable that has not yet been declared, the variable will automatically be declared as a GLOBAL variable.
  • 42. JAVASCRIPT OPERATORS  = is used to assign values.  The assignment operator = is used to assign values to JavaScript variables.  + is used to add values.  The arithmetic operator + is used to add values together.
  • 43. ARITHMETIC OPERATOR  Operator example x y  + Addition x=y+2 7 5  - Subtraction x=y-2 3 5  * Multiplication x=y*2 10 5  / Division x=y/2 2.5 5  % Modulus x=y%2 1 5  ++ Increment x=++y 6 6 x=y++ 5 6 -- Decrement x=--y 4 4 x=y-- 5 4
  • 44. THE + OPERATOR USED ON STRINGS  txt1="What a very"; txt2="nice day"; txt3=txt1+txt2;
  • 45. ADDING STRINGS AND NUMBERS  x=5+5; y="5"+5; z="Hello"+5;  output  10 55 Hello5
  • 46. COMPRESSION OPERATOR  == is equal to  === is exactly equal to (value and type)  != is not equal  !== is not equal (neither value nor type)  > is greater than  < is less than  >= is greater than or equal to  <= is less than or equal to
  • 47. LOGICAL OPERATORS  && and (x < 10 && y > 1)  || or (x==5 || y==5)  ! not !(x==y)  Consider x = 6 and y = 3
  • 48. CONDITIONAL OPERATOR  JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.  Syntax  Variable name=(condition)?value1:value2  Example voteable=(age<18)?"Too young":"Old enough";
  • 49. CONDITIONAL STATEMENTS  Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
  • 50. CONDITIONAL STATEMENTS CONT..  In JavaScript we have the following conditional statements:  if statement - use this statement to execute some code only if a specified condition is true  if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false  if...else if....else statement - use this statement to select one of many blocks of code to be executed  switch statement - use this statement to select one of many blocks of code to be executed
  • 51. IF STATEMENT  if (condition) { code to be executed if condition is true }
  • 52. IF…ELSE  if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true }
  • 53. IF … ELSE IF … ELSE  if (condition1) { code to be executed if condition1 is true } else if (condition2) { code to be executed if condition2 is true } else { code to be executed if neither condition1 nor condition2 is true }
  • 54. THE JAVASCRIPT SWITCH STATEMENT  switch(n) { case 1: execute code block 1 break; case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 }
  • 55. JAVASCRIPT LOOPS  Loops are handy, if you want to run the same code over and over again, each time with a different value.
  • 56. PROBLEM  document.write(cars[0] + "<br>"); document.write(cars[1] + "<br>"); document.write(cars[2] + "<br>"); document.write(cars[3] + "<br>"); document.write(cars[4] + "<br>"); document.write(cars[5] + "<br>"); document.write(cars[6] + "<br>"); document.write(cars[7] + "<br>"); document.write(cars[8] + "<br>"); document.write(cars[9] + "<br>"); document.write(cars[10] + "<br>");
  • 57. SOLUTION  for (var i=0;i<=10;i++) { document.write(cars[i] + "<br>"); }
  • 58. THE FOR LOOP  for (variable initialization ; Condition Checking ; increment or decrement ) { the code block to be executed }
  • 59. THE WHILE LOOP  while (condition) { code block to be executed }
  • 60. THE DO WHILE LOOP  do { code block to be executed } while (condition);
  • 61. JAVASCRIPT BREAK AND CONTINUE  The Break Statement  You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch() statement.  The break statement can also be used to jump out of a loop.  The break statement breaks the loop and continues executing the code after the loop (if any):
  • 62. EXAMPLE  for (i=0;i<10;i++) { if (i==3) { break; } x=x + "The number is " + i + "<br>"; }
  • 63. THE CONTINUE STATEMENT  The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
  • 64. EXAMPLE  for (i=0;i<=10;i++) { if (i==3) continue; x=x + "The number is " + i + "<br>"; }
  • 65. JAVA SCRIPT LABELS  break labelname; continue labelname;
  • 66. JAVA SCRIPT LABELS EXAMPLE  cars=["BMW","Volvo","Saab","Ford"]; list: { document.write(cars[0] + "<br>"); document.write(cars[1] + "<br>"); document.write(cars[2] + "<br>"); break list; document.write(cars[3] + "<br>"); document.write(cars[4] + "<br>"); document.write(cars[5] + "<br>"); }
  • 67. JAVA SCRIPT ERROR HANDLING  The try statement lets you to test a block of code for errors.  The catch statement lets you handle the error.  The throw statement lets you create custom errors.
  • 68. ERRORS WILL HAPPEN!  When the JavaScript engine is executing JavaScript code, different errors can occur:  It can be syntax errors, typically coding errors or typos made by the programmer.  It can be misspelled or missing features in the language (maybe due to browser differences).  It can be errors due to wrong input, from a user, or from an Internet server.  And, of course, it can be many other unforeseeable things.
  • 69. JAVASCRIPT THROWS ERRORS  When an error occurs, when something goes wrong, the JavaScript engine will normally stop, and generate an error message.  The technical term for this is: JavaScript will throw an error.
  • 70. JAVASCRIPT TRY AND CATCH  The try statement allows you to define a block of code to be tested for errors while it is being executed.  The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.  The JavaScript statements try and catch come in pairs.
  • 71. SYNTAX  try { //Run some code here } catch(err) { //Handle errors here }
  • 72. EXAMPLE  <script> var txt=""; function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.nn"; txt+="Error description: " + err.message + "nn"; txt+="Click OK to continue.nn"; alert(txt); } } </script>  <input type="button" value="View message" onclick="message()">
  • 73. THE THROW STATEMENT  The throw statement allows you to create a custom error.  The correct technical term is to create or throw an exception.  If you use the throw statement together with try and catch, you can control program flow and generate custom error messages.
  • 74. EXAMPLE  script> function myFunction() { try { var x=document.getElementById("demo").value; if(x=="") throw "empty"; if(isNaN(x)) throw "not a number"; if(x>10) throw "to high"; if(x<5) throw "too low"; } catch(err) { var y=document.getElementById("mess"); y.innerHTML="Error: " + err + ".";} } } </script> <p>Please input a number between 5 and 10:</p> <input id="demo" type="text"> <button type="button" onclick="myFunction()">Test Input</button> <p id="mess"></p>
  • 75. JAVASCRIPT FORM VALIDATION  JavaScript can be used to validate data in HTML forms before sending off the content to a server.  Form data that typically are checked by a JavaScript could be:  has the user left required fields empty?  has the user entered a valid e-mail address?  has the user entered a valid date?  has the user entered text in a numeric field?
  • 76. NULL FIELDS  function validateForm() { var x=document.forms["myForm"]["fname"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } }
  • 77. E-MAIL VALIDATION  function validateForm() { var x=document.forms["myForm"]["email"].value; var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Not a valid e-mail address"); return false; } }
  • 78. THE HTML DOM (DOCUMENT OBJECT MODEL)  When a web page is loaded, the browser creates a Document Object Model of the page.
  • 80. WITH THE DOM  With a programmable object model, JavaScript gets all the power it needs to  create dynamic HTML:  JavaScript can change all the HTML elements in the page  JavaScript can change all the HTML attributes in the page  JavaScript can change all the CSS styles in the page  JavaScript can react to all the events in the page
  • 81. FINDING HTML ELEMENTS  Often, with JavaScript, you want to manipulate HTML elements.  To do so, you have to find the elements first. There are a couple of ways to do this:  Finding HTML elements by id  Finding HTML elements by tag name  Finding HTML elements by class name
  • 82. FINDING HTML ELEMENTS BY ID  var x=document.getElementById("intro");
  • 83. FINDING HTML ELEMENTS BY TAG NAME  var x=document.getElementById("main"); var y=x.getElementsByTagName("p");
  • 84. CHANGING THE HTML OUTPUT STREAM  <body> <script> document.write(Date()); </script> </body>
  • 85. CHANGING HTML CONTENT  The easiest way to modify the content of an HTML element is by using the innerHTML property.  To change the content of an HTML element, use this syntax:  document.getElementById(id).innerHTML=  new HTML
  • 86. EXAMPLE  <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML="New text!"; </script>
  • 87. CHANGING AN HTML ATTRIBUTE  To change the attribute of an HTML element, use this syntax:  document.getElementById(id).attribute=new value
  • 88. EXAMPLE  <img id="image" src="smiley.gif"> <script> document.getElementById("image").src="landscape .jpg"; </script>
  • 89. EVENTS  A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.  To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:  Example :  onclick=JavaScript
  • 90.  When a user clicks the mouse  When a web page has loaded  When an image has been loaded  When the mouse moves over an element  When an input field is changed  When an HTML form is submitted  When a user strokes a key
  • 92. THE ONLOAD AND ONUNLOAD EVENTS  he onload and onunload events are triggered when the user enters or leaves the page.  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.
  • 93. EXAMPLE  <body onload=“viewdate()">  <script>  Function viewdate()  {  alert(date());  }  </script>
  • 94. ON MOUSE OVER  The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an HTML element.
  • 95. EXAMPLE  <div onmouseover="mOver(this)" onmouseout="mOut(this)" style="background- color:#D94A38;width:120px;height:20px;padding:40px;">Mouse Over Me</div>  <script>  function mOver(obj)  {  obj.innerHTML="Thank You"  }  function mOut(obj)  {  obj.innerHTML="Mouse Over Me"  }  </script>
  • 96. THE ONMOUSEDOWN, ONMOUSEUP AND ONCLICK EVENTS  The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is triggered.
  • 97. EXAMPLE  <div onmousedown="mDown(this)" onmouseup="mUp(this)" style="background- color:#D94A38;width:90px;height:20px;padding:40px;">Click Me</div>  <script>  function mDown(obj)  {  obj.style.backgroundColor="#1ec5e5";  obj.innerHTML="Release Me"  }  function mUp(obj)  {  obj.style.backgroundColor="#D94A38";  obj.innerHTML="Thank You"  }  </script>
  • 98. CREATING NEW HTML ELEMENTS  To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
  • 99. EXAMPLE  <div id="d1">  <p id="p1">This is a paragraph.</p>  <p id="p2">This is another paragraph.</p>  </div>  <script>  var para=document.createElement("p");  var node=document.createTextNode("This is new.");  para.appendChild(node);  var element=document.getElementById("d1");  element.appendChild(para);  </script>
  • 100. REMOVING EXISTING HTML ELEMENTS  To remove an HTML element, you must know the parent of the element:
  • 101. EXAMPLE  <div id="d1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div><script> var parent=document.getElementById("d1"); var child=document.getElementById("p1"); parent.removeChild(child); </script>
  • 102. THE JAVA SCRIPT OBJECT  JavaScript has several built-in objects, like String, Date, Array, and more.  An object is just a special kind of data, with properties and methods
  • 103. CREATING JAVASCRIPT OBJECTS  With JavaScript you can define and create your own objects.  There are 2 different ways to create a new object:  1. Define and create a direct instance of an object.  2. Use a function to define an object, then create new object instances.
  • 104. CREATING A DIRECT INSTANCE  person=new Object(); person.firstname="John"; person.lastname="Doe"; person.age=50; person.eyecolor="blue";
  • 105. USING AN OBJECT CONSTRUCTOR  function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; }  var myFather=new person("John","Doe",50,"blue"); var myMother=new person("Sally","Rally",48,"green");
  • 106. ADDING METHODS TO JAVASCRIPT OBJECTS  function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; this.changeName=changeName;  function changeName(name) { this.lastname=name; } }
  • 107. JAVASCRIPT CLASSES  JavaScript is an object oriented language, but JavaScript does not use classes.  In JavaScript you don’t define classes and create objects from these classes (as in most other object oriented languages).  JavaScript is prototype based, not class based.
  • 108. JAVASCRIPT FOR...IN LOOP  The JavaScript for...in statement loops through the properties of an object.  Syntax  for (variable in object) { code to be executed }
  • 109. EXAMPLE  var person={fname:"John",lname:"Doe",age:25}; for (x in person) { txt=txt + person[x]; }
  • 110. JAVASCRIPT NUMBERS  var pi=3.14; // Written with decimals var x=34; // Written without decimals  All JavaScript Numbers are 64-bit  JavaScript is not a typed language. Unlike many other programming languages, it does not define different types of numbers, like integers, short, long, floating-point etc.
  • 111. JAVASCRIPT STRINGS  A string simply stores a series of characters like "John Doe".  A string can be any text inside quotes. You can use simple or double quotes:  var carname="Volvo XC60"; var carname='Volvo XC60';
  • 112.  You can access each character in a string with its position (index):  Example  var character=carname[7];
  • 113. STRING METHODS  charAt() charCodeAt()  concat() fromCharCode()  indexOf() lastIndexOf()  match() replace()  search() slice()  split() substr()  substring() toLowerCase()  toUpperCase() valueOf()
  • 114. DATE OBJECT  Date()  Returns current date and time  getFullYear() Use getFullYear() to get the year.  getTime() getTime() returns the number of milliseconds since 01.01.1970.
  • 115. SET A DATE  var myDate=new Date(); myDate.setFullYear(2010,0,14);  And also  var myDate=new Date(); myDate.setDate(myDate.getDate()+5);
  • 116. COMPARE TWO DATES  var x=new Date(); x.setFullYear(2100,0,14); var today = new Date(); if (x>today) { alert("Today is before 14th January 2100"); } else { alert("Today is after 14th January 2100"); }
  • 117. ARRAY  An array is a special variable, which can hold more than one value at a time.  If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:  var car1="Saab"; var car2="Volvo"; var car3="BMW";  However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?  The solution is an array!
  • 118. YOU CAN HAVE DIFFERENT OBJECTS IN ONE ARRAY  myArray[0]=Date.now; myArray[1]=myFunction; myArray[2]=myCars;
  • 119. CREATING ARRAY  1: Regular:  var myCars=new Array(); myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW";  2: Condensed:  var myCars=new Array("Saab","Volvo","BMW");  3: Literal:  var myCars=["Saab","Volvo","BMW"];
  • 120. ARRAY METHODS AND PROPERTIES  Property length  Methods  indexOf() concat()  Join() pop()  push() reverse()  shift() slice()  sort() splice()  toString() unshift()
  • 121. BOOLEAN  There is only Two states  True  False
  • 122. MATH FUNCTIONS  abs() ceil()  exp() floor()  max() min()  pow() random()  round() sqrt()
  • 123. REGULAR EXPRESSION  A regular expression is an object that describes a pattern of characters.  When you search in a text, you can use a pattern to describe what you are searching for.  A simple pattern can be one single character.  A more complicated pattern can consist of more characters, and can be used for parsing, format checking, substitution and more.  Regular expressions are used to perform powerful pattern-matching and "search-and-replace" functions on text.
  • 124. SYNTAX  var patt=new RegExp(pattern,modifiers); or more simply: var patt=/pattern/modifiers;  pattern specifies the pattern of an expression  modifiers specify if a search should be global, case- sensitive, etc.
  • 125. MODIFIERS  Modifiers are used to perform case-insensitive and global searches.  The i modifier is used to perform case-insensitive matching.  The g modifier is used to perform a global match (find all matches rather than stopping after the first match).
  • 126. EXAMPLE  <script>  var str = "Visit W3Schools";  var patt1 = /w3schools/i;  document.write(str.match(patt1));  </script>
  • 127. EXAMPLE 2  <script>  var str="Is this all there is?";  var patt1=/is/g;  document.write(str.match(patt1));  </script>
  • 128. EXAMPLE  <script>  var str="Is this all there is?";  var patt1=/is/gi;  document.write(str.match(patt1));  </script>
  • 129. TEST()  The test() method searches a string for a specified value, and returns true or false, depending on the result.
  • 130. EXAMPLE  <script>  var patt1=new RegExp("e");  document.write(patt1.test("The best things in life are free"));  </script>  </body>
  • 131. EXEC()  The exec() method searches a string for a specified value, and returns the text of the found value. If no match is found, it returns null.
  • 132. EXAMPLE  <script>  var patt1=new RegExp("e");  document.write(patt1.exec("The best things in life are free"));  </script>
  • 133. JAVA SCRIPT OBJECTS  Window Object  Screen Object  History Object  Navigator Object  Popupalert Object  Timing Object  Cookie Object
  • 134. WINDOW OBJECT  The window object is supported by all browsers. It represent the browsers window.  All global JavaScript objects, functions, and variables automatically become members of the window object.  Global variables are properties of the window object.  Global functions are methods of the window object.  Even the document object (of the HTML DOM) is a property of the window object:
  • 135. WINDOW SIZE  Three different properties can be used to determine the size of the browser window (the browser viewport, NOT including toolbars and scrollbars).  For Internet Explorer, Chrome, Firefox, Opera, and Safari:  window.innerHeight - the inner height of the browser window  window.innerWidth - the inner width of the browser window  For Internet Explorer 8, 7, 6, 5:  document.documentElement.clientHeight  document.documentElement.clientWidth
  • 136. OTHER WINDOW METHODS  window.open() - open a new window  window.close() - close the current window  window.moveTo() -move the current window  window.resizeTo() -resize the current window
  • 137. WINDOW SCREEN OBJECT  The window.screen object can be written without the window prefix.  document.write("Available Width: " + screen.availWidth); document.write("Available Height: " + screen.availHeight);
  • 138. EXAMPLE  <h3>Your Screen:</h3>  <script>  document.write("Total width/height: ");  document.write(screen.width + "*" + screen.height);  document.write("<br>");  document.write("Available width/height: ");  document.write(screen.availWidth + "*" + screen.availHeight);  document.write("<br>");  document.write("Color depth: ");  document.write(screen.colorDepth);  document.write("<br>");  document.write("Color resolution: ");  document.write(screen.pixelDepth);  </script>
  • 139. LOCATION OBJECT  The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.
  • 140.  location.hostname returns the domain name of the web host  location.path returns the path and filename of the current page  location.port returns the port of the web host (80 or 443)  location protocol returns the web protocol used (http:// or https://)
  • 141. EXAMPLE  document.write(location.href);  document.write(location.pathname);  function newDoc() { window.location.assign("http://www. w3schools.com"); }
  • 142. HISTORY OBJECT  To protect the privacy of the users, there are limitations to how JavaScript can access this obje  history.back() - same as clicking back in the browser  history.forward() - same as clicking forward in the browser
  • 146. WARNING !!!  The information from the navigator object can often be misleading, and should not be used to detect browser versions because:  The navigator data can be changed by the browser owner  Some browsers misidentify themselves to bypass site tests  Browsers cannot report new operating systems, released later than the browser
  • 147. POPUP BOXES  JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
  • 148. ALERT BOX  An alert box is often used if you want to make sure information comes through to the user.  When an alert box pops up, the user will have to click "OK" to proceed.  Syntax  window.alert("sometext");
  • 149. EXAMPLE  <head> <script> function myFunction() { alert("I am an alert box!"); } </script> </head> <body> <input type="button" onclick="myFunction()" value="Show alert box"> </body>
  • 150. CONFIRM BOX  A confirm box is often used if you want the user to verify or accept something.  When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.  If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false  Syntax  window.confirm("sometext");
  • 151. EXAMPLE  var r=confirm("Press a button"); if (r==true) { x="You pressed OK!"; } else { x="You pressed Cancel!"; }
  • 152. PROMPT BOX  A prompt box is often used if you want the user to input a value before entering a page.  When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.  If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.  Syntax  window.prompt("sometext","defaultvalue");
  • 153. EXAMPLE  var name=prompt("Please enter your name","Harry Potter");  if (name!=null && name!="") { x="Hello " + name + "! How are you today?"; }
  • 154. LINE BREAKS  To display line breaks inside a popup box, use a back-slash followed by the character n.  Example  alert("Hellon How are you?");
  • 155. JAVASCRIPT TIMING EVENTS  With JavaScript, it is possible to execute some code at specified time-intervals. This is called timing events.  It's very easy to time events in JavaScript. The two key methods that are used are:  setInterval() - executes a function, over and over again, at specified time intervals  setTimeout() - executes a function, once, after waiting a specified number of milliseconds
  • 156. SETINTERVAL()  The setInterval() Method  The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.  Syntax  window.setInterval("javascript function",milliseconds);
  • 157. EXAMPLE  1) setInterval(function(){alert("Hello")},3000);  2)  var myVar= setInterval(function() {myTimer()},  1000); function myTimer() { var d=new Date(); var t=d.toLocaleTimeString(); document.getElementById("demo")  . innerHTML=t; }
  • 158. HOW TO STOP THE EXECUTION?  The clearInterval() method is used to stop further executions of the function specified in the setInterval() method.  Syntax  window.clearInterval(intervalVariable)
  • 160. HOW TO STOP THE EXECUTION?  The clearTimeout() method is used to stop the execution of the function specified in the setTimeout() method.  Syntax  window.clearTimeout(timeoutVariable)
  • 161. COOKIES  A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.