0% found this document useful (0 votes)
17 views

Javascript 161204063332

Uploaded by

Mweene Mweemba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Javascript 161204063332

Uploaded by

Mweene Mweemba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 161

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.\n\n";
txt+="Error description: " + err.message + "\n\n";
txt+="Click OK to continue.\n\n";
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

Elements Forms

Elements Forms
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("Hello\n 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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy