Javascript 161204063332
Javascript 161204063332
<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.
document.getElementById("demo").innerHTML="H
ello Word";
SEMICOLON ;
Semicolon separates JavaScript statements.
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
var carname;
carname = “Volvo”;
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 };
name=person.lastname;
name=person["lastname"];
DECLARING VARIABLE TYPES
When you declare a new variable, you can declare
its type using the "new" keyword:
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
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.
Window
Document
Elements Forms
Elements Forms
WITH THE DOM
With a programmable object model, JavaScript gets
all the power it needs to
<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
<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
<script>
function mOver(obj)
{
obj.innerHTML="Thank You"
}
function mOut(obj)
{
obj.innerHTML="Mouse Over Me"
}
</script>
THE ONMOUSEDOWN, ONMOUSEUP AND
ONCLICK EVENTS
<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:
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
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
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.
or more simply:
var patt=/pattern/modifiers;
<script>
var str = "Visit W3Schools";
document.write(str.match(patt1));
</script>
EXAMPLE 2
<script>
document.write(str.match(patt1));
</script>
EXAMPLE
<script>
document.write(str.match(patt1));
</script>
TEST()
<script>
var patt1=new RegExp("e");
</body>
EXEC()
<script>
var patt1=new RegExp("e");
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.
<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
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
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:
Syntax
window.alert("sometext");
EXAMPLE
<head>
<script>
function myFunction()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
</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");
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:
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.