Javascri P
Javascri P
Javascri P
1
what can you do with JavaScript?
Validate form fields
Dynamically alter the appearance of a page element
Hide and show elements
Move elements about the page
Capture user events and adjust the page accordingly
Interface with a server-side application without leaving the page
Set and retrieve web cookies
2
"Hello World!"
Javascript is easy
Script tags are added to the head/body element in the document
<script type="text/javascript">
...some JavaScript
</script>
3
JavaScript Code Location
Place the JavaScript in the body
when the JavaScript dynamically creates web
page content as the page is being loaded.
Place the JavaScript in the head tag
When the JavaScript defined in functions and
used for page events, as this is loaded before the
body.
4
Eg
5
JavaScript Files
To include a JavaScript library or script file in your web
page, use this syntax:
<script type="text/javascript" src="somejavascript.js"></script>
The script element contains no content, but the closing
tag is still required
A script file is treated as if the code is actually included in
the page; the behavior is the same between script files and
embedded JavaScript blocks.
6
JavaScript Data Types and
Variables
7
Data Types
JavaScript is forgiving
If you start out with a string => then want to use
it as a number, that's perfectly fine with the
language.
Context is everything when it comes to JavaScript data
typing/ variable.
Because JavaScript is case-sensitive, variable names are
case-sensitive.
There are just three simple data types:
string,
numeric, and
Boolean.
8
String Data Type
A string literal is a sequence of characters delimited by
single or double quotes:
"This is a string"
'But this is also a string'
var string_value = "This is the first line\nThis is the
second line";
to include a quote within the quoted string,
Use a single and double quotes can be used
interchangeably
var string_value = "This is a 'string' with a quote."
or:
var string_value = 'This is a "string" with a quote.'
9
Number Data Type
Numbers in JavaScript are floating-point numbers,
All of the following are valid floating-point numbers:
0.3555 , 144.006 , -2.3 , 19.5e-2 (which is equivalent to 19.5-2)
10
Null and Undefined
Not declared
alert(sValue); // results in JavaScript error
because sValue is not declared first
A null variable is one that has been defined, but hasn't been
assigned a value.
var sValue;
alert(sValue); // no error, and a window with
the word 'undefined' is opened
If the variable has been declared but not initialized, it is
considered undefined
Constants
const CURRENT_MONTH = 3.5;
11
Changing data types
parseInt and
Function toString toBoolean
parseFloat
1 if true ;
Boolean “true” / “false” Value of value
otherwise 0
false if 0 or NaN;
Number String number Straight value
otherwise, TRue
false if string
String No conversion is empty; Number portion
otherwise, true
A string Numeric
representation representation of
Object of the default TRue the default
representation representation of
of the object the object 12
Operators and Statements
13
Simple Statements
Assignment
NValue = 35.00;
nValue = nValue + 35.00;
nValue = someFunction( );//function call
var firstName = lastName = middleName =
""; //more than one assignment is
possible
Arithmetic Statements
Concatenation ( “+” used with string)
var newString = "This is an old " + oldString;
Multiplication ( “*” used with numbers)
var newValue = 3.5 * 2.0; // result is 7
var newValue = 3.5 * "2.0"; // result is still 7
14
var newValue = "3.5" * "2.0"; // still 7
Cont'd . . . Simple Statements
Since + is used as a concatenation with string.
var newValue = 3.5 + "2.0"; // result is 3.52.0
Better way to use is by explicitly converting the value
var aVar = 3.5 + parseFloat("2.3 the sum is ");
document.write(aVar); // result is 5.8
The Unary Operators
++ Increments a value
-- Decrements a value
- Represents a negative value
15
Conditional Statements and Program Flow
if
if...else
Switch
Ternary Operator
condition ? value if true; value if false;
Logical Operators
AND (&&) , OR (||) , NOT(!)
16
The Loops
While
do...while
For ( two types )
First type
For (initial value; condition; update) {
… }
second type of the for loop is a for...in loop
which accesses each element of the array
as a separate item. The syntax for this
handy statement is:
for (variable in object) {
...
17
}
Eg for in loop
<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html
18
JavaScript Popup Boxes
three kinds of popup boxes: Alert box, Confirm box, and Prompt
box.
Alert Box
Used if you want to make sure information
comes through to the user.
alert("sometext");
Confirm Box
used if you want the user to verify or
accept something.
confirm("sometext");
Prompt Box
used if you want the user to input a value
before entering a page.
prompt("sometext","defaultvalue");
19
Eg Alert box
<html>
<head>
<script type="text/javascript">
function disp_alert() {
alert("I am an alert box!!");
}
</script>
</head>
<body>
<input type="button"
onclick="disp_alert()"
value="Display alert box" />
</body>
</html>
20
Eg Confirm Box
html>
<head>
<script type="text/javascript">
function disp_confirm() {
var r=confirm("Press a button");
if (r==true) {
document.write("You pressed OK!");
}
Else {
document.write("You pressed Cancel!");
}
}
</script>
</head>
<body>
<input type="button" onclick="disp_confirm()"
value="Display a confirm box" />
</body>
21
</html>
Eg prompt box
<html>
<head>
<script type="text/javascript">
function disp_prompt()
{
var name=prompt("Please enter your
name","Harry Potter");
if (name!=null && name!="") {
document.write("Hello " + name + "! How are you today?");
}
}
</script>
</head>
<body>
</body>
22
</html>
The JavaScript Objects
23
Objects from four different domains
Those built into JavaScript
are those that are built into JavaScript as
language-specific components
Eg: data types Numbers, Strings, Boolaean
special-purpose objects, such as Math, Date,
and RegExp.
built-in aggregator object, Array
24
An object
An object has properties and methods .
Properties
values associated with an object.
var txt="Hello World!";
document.write(txt.length); // result 12
methods
actions that can be performed on objects
var str="Hello world!";
document.write(str.toUpperCase()); //result HELLO
WORLD!
25
The Number Object
The object also has four constant numeric properties, directly
accessible from the Number object.
MAX_VALUE - Returns the largest possible value in JavaScript
MIN_VALUE - Returns the smallest possible value in JavaScript
NEGATIVE_INFINITY -Represents a value that is less than
MIN_VALUE 4
POSITIVE_INFINITY -Represents a value that is greater than
MAX_VALUE
The Number object's unique methods
ToExponential() - Converts the value of the object into an exponential
notation
ToFixed() - Formats a number to the specified number of decimals
ToPrecision() - Converts a number into a number with a specified number
of digits
ToString() - Converts the Number object into a string
ValueOf() - Returns the value of the Number object
26
Eg
27
The String Object
is used to manipulate a stored piece of text.
Created by:
var sObject = new String("Sample string"); // OR
var sObject = "Sample string";
Eg Methods: the concat method
var sObj = new String( );
var sTxt = sObj.concat("This is a ", "new string");
Result:
This is a new string
The indexOf() method
Used to return the position of the first occurrence of a specified
string value in a string.
var str="Hello world!";
document.write(str.indexOf("Hello") + "<br />"); Result:
document.write(str.indexOf("World") + "<br />"); 0
document.write(str.indexOf("world")); -1 none
6 28
String Object methods
Eg match(): similar to indexOf() and lastIndexOf(), but it
returns the specified value, instead of the position of the
string.
var str="Hello world!"; Result:
document.write(str.match("world") + "<br />"); world
document.write(str.match("World") + "<br />"); null
document.write(str.match("worlld") + "<br />"); null
document.write(str.match("world!")); world!
29
Result:
Visit Sun!
Cont'd ... String Object methods
Method Description
anchor() Creates an HTML anchor
big() Displays a string in a big font
blink() Displays a blinking string
bold() Displays a string in bold
charAt() Returns the character at a specified position
charCodeAt() Returns the Unicode of the character at a specified
position
concat() Joins two or more strings
fixed() Displays a string as teletype text
fontcolor() Displays a string in a specified color
fontsize() Displays a string in a specified size
fromCharCode() Takes the specified Unicode values and returns a
string
indexOf() Returns the position of the first occurrence of a specified
string value in a string
30
Cont'd ... String Object methods
italics() Displays a string in italic
lastIndexOf() Returns the position of the last occurrence of a
specified string value, searching backwards from the specified position in
a string
link() Displays a string as a hyperlink
match() Searches for a specified value in a string
replace() Replaces some characters with some other characters in a
string
search() Searches a string for a specified value
slice() Extracts a part of a string and returns the extracted part in a new
string
small() Displays a string in a small font
split() Splits a string into an array of strings
strike() Displays a string with a strikethrough
sub() Displays a string as subscript
31
Cont'd ... String Object methods
substr() Extracts a specified number of characters in a string, from
a start index
substring() Extracts the characters in a string between two specified
indices
sup() Displays a string as superscript
toLowerCase() Displays a string in lowercase letters
toUpperCase() Displays a string in uppercase letters
toSource() Represents the source code of an object
valueOf() Returns the primitive value of a String object
32
Eg styling text
var txt="Hello World!";
document.write("<p>Big: " + txt.big() + "</p>");
document.write("<p>Small: " + txt.small() + "</p>");
Output: s 115
34
Cont'd . . . String methods
The substr and substring methods, as well as slice, return a
substring given a starting location and length of string:
The start index starts at 0.
stringObject.substring(start,stop)
var sTxt = "This is a test string";
var ssTxt = sTxt.substr(0,6);
Var sssTxt = sTxt.substring(0,9)
document.writeln(ssTxt);
document.writeln(sssTxt);
Result:
How,are,you,doing,today?
36
H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?
How,are,you
eg
var inputString =
'firstName=Shelley,lastName=Powers,state=Missour
i,statement="This is a test of split"';
var arrayTokens = inputString.split(',',4);
for (var i in arrayTokens) {
document.writeln(arrayTokens[i] + "<br />");
var newTokens = arrayTokens[i].split('=');
document.writeln(newTokens[1] + "<br />");
}
Result :
firstName=Shelley
Shelley
lastName=Powers
Powers
state=Missouri
Missouri
statement="This is a test of split"
"This is a test of split" 37
Date objects
The Date
create a date and then access any aspect of it
year, day, second, and so on.
var dtNow = new Date( );
document.writeln(dtNow);
Output:
Thu Apr 2 2009 12:08:38 GMT+0300
to create a specific date (use proper format!)
var nowDt = new Date("March 12, 1984 12:20:25");
var newDt = new Date(1977,12,23);
var newDt = new Date(1977,11,24,19,30,30,30);
in order of year, month (as 0 to 11), day, hour, minutes,
seconds, and milliseconds. 38
Date Objects
The Date object methods get and set specific components
of the date
getFullYear
getHours
getMilliseconds
getMinutes
getMonth
getSeconds
GetYear
eg.
var dtNow = new Date( );
alert(dtNow.getDay( )); // if run on friday result:5
39
Compare Two Dates
if (myDate>today) {
document.write("Today is before 14th January 2010");
}
Else {
document.write("Today is after 14th January 2010");
}
40
An array to write a weekday
<html>
<body>
<script type="text/javascript">
var d=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday"; Result: Today it is Friday
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
document.write("Today it is " + weekday[d.getDay()]);
</script>
41
</body>
</html>
Math objects
allows you to perform mathematical tasks
Math's properties and methods are static (can not create new
instance)
var newValue = Math.SQRT1;
Math's properties
To access use Math.property
E - Value of e, the base of the natural logarithms
LN10 - The natural logarithm of 10
LN2 - The natural logarithm of 2
LOG2E - The approximate reciprocal of LN2the base-2
logarithm of e
LOG10E - The approximate reciprocal of LN10the
base-10 logarithm of e
PI - The value of PI
SQRT1_2 - The square root of 1/2 42
SQRT2 - The square root of 2
Cont'd . . . Math objects
The Math Methods
Math.abs( ) - Computes an absolute value.
Math.ceil( ) - Rounds a number up. eg.
Math.cos( )- Computes a cosine. var nVal = -3.45;
Math.exp( ) - Computes a power of e. var pVal = Math.abs(nVal);
Math.floor( ) - Rounds a number down.
Math.log( ) - document.write(Math.round(4.7));
Computes a natural logarithm.
Output: 5
Math.max( ) - Returns the larger of two numbers.
Math.min( ) - Returns the smaller of two numbers.
Math.pow( ) - Computes x^y
Math.random( ) - Computes a random number.
Math.round( ) - Rounds to the nearest integer.
Math.sin( ) - Computes a sine.
Math.sqrt( ) - Computes a square root.
Math.tan( ) - Computes a tangent
43
eg.
44
JavaScript Arrays
Constructing Arrays
with a constructor
var newArray = new Array('one','two');
As a literal value
var newArray = ['one','two'];
Multi-dimensional array
var threedPoints = new Array( );
threedPoints[0] = new Array(1.2,3.33,2.0);
threedPoints[1] = new Array(5.3,5.5,5.5);
threedPoints[2] = new Array(6.4,2.2,1.9);
document.writeln(threedPoints[0][1]);
45
Output : 3.33
Array properties
length – the length of an array
var testArray = new Array( );
testArray[99] = 'some value'; //set size 100
alert(testArray.length);
Output: 100
Splice - returns selected elements from an existing array.
var fruitArray = new
Array('apple','peach','orange','lemon','lime','cherry'
);
var removed = fruitArray.splice(2,2,'melon,banana');
document.writeln(removed + "<br />");
document.writeln(fruitArray);
Output:
orange,lemon 46
apple,peach,melon,banana,lime,cherry
Array
Concat - concatenates one array onto the end of the other:
var arr = new Array(3);
arr[0] = "Jani";
arr[1] = "Tove";
arr[2] = "Hege"; Output:
Jani,Tove,Hege,John,Andy,Wend
var arr2 = new Array(3); y
arr2[0] = "John";
arr2[1] = "Andy";
arr2[2] = "Wendy";
document.write(arr.concat(arr2));
48
Literal array - sort()
var arr = new Array(6);
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";
arr[5] = "Tove";
Output:
Jani,Hege,Stale,Kai Jim,Borge,Tove
Borge,Hege,Jani,Kai Jim,Stale,Tove
49
Associative Arrays
doesn't have a numeric index
Object is normally used
var assocArray = new Object( );
assocArray["one"] = "Show one";
assocArray["two"] = "Show two";
document.writeln(assocArray["two"]<br />);
document.writeln(assocArray.one);//accessed as object
Output:
Show two
Show one 50
JavaScript Applications
51
Browser Detection by Navigator object
JavaScript includes an object called the Navigator object
which contains information about the visitor's browser
name, browser version, and more.
appName Returns the name of the browser
appVersion Returns the platform and version of the browser
browserLanguage Returns the current browser language
cookieEnabled Returns a Boolean value that specifies whether
cookies are enabled in the browser
platform Returns the operating system platform
systemLanguage Returns the default language used by the OS
52
Browser Detection
<html>
<body>
<script type="text/javascript">
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(b_version);
54
Eg form Validation
<body>
<html> <form action="submitpage.htm"
<head> onsubmit="return
<script type="text/javascript"> validate_form(this)"
function validate_required(field,alerttxt) method="post">
{ Email: <input type="text"
with (field) { name="email" size="30">
if (value==null||value=="") <input type="submit"
{alert(alerttxt); return false;} value="Submit">
else {return true} </form>
} </body>
}
</html>
function validate_form(thisform) {
with (thisform) {
if (validate_required(email,"Email must be filled
out!")==false)
{email.focus();return false;}
}
}
55
</script>
</head>
<html>
<head>
<script language = "Javascript">
Email Validation
function echeck(str) {
var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){
alert("Invalid E-mail ID")
return false }
if (str.indexOf(at,(lat+1))!=-1){
alert("Invalid E-mail ID")
return false }
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(dot,(lat+2))==-1){
alert("Invalid E-mail ID")
return false }
if (str.indexOf(" ")!=-1){
alert("Invalid E-mail ID") 56
return false }
return true
}
Email validation
function ValidateForm(){
var emailID=document.frmSample.txtEmail
if ((emailID.value==null)||(emailID.value=="")){
alert("Please Enter your Email ID")
emailID.focus()
return false
}
if (echeck(emailID.value)==false){
emailID.value=""
emailID.focus()
return false
}
return true
}
</script>
</head>
<body>
</html>
<html> JavaScript Animation
<head>
<script type="text/javascript">
function mouseOver()
{
document.b1.src ="b_blue.gif";
}
function mouseOut()
{
document.b1.src ="b_pink.gif";
}
</script>
</head>
<body>
<a href="http://www.w3schools.com" target="_blank">
<img border="0" alt="Visit W3Schools!"
src="b_pink.gif" name="b1"
onmouseOver="mouseOver()"
onmouseOut="mouseOut()" />
</a> 58
</body>
</html>
DOM
59
Document Object Model
The HTML Document Object Model (HTML DOM) defines a
standard way for accessing and manipulating HTML documents.
60
What is the DOM?
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents like HTML
and XML:
61
HTML DOM Nodes
In the DOM, everything in an HTML document is a node.
The DOM says:
The entire document is a document node
Every HTML tag is an element node
The text in the HTML elements are text nodes
Every HTML attribute is an attribute node
Comments are comment nodes
Eg
<html>
<head>
The root node in the HTML above is <html>.
<title>DOM Tutorial</title> All other nodes in the document are
</head> contained within <html>.
<body>
<h1>DOM Lesson one</h1> The <html> node has two child nodes;
<head> and <body>.
<p>Hello world!</p>
</body> The <head> node holds a <title> node.
</html> The <body> node holds a <h1> and <p>
node. 62
HTML DOM Node Tree
The HTML DOM views a HTML document as a tree-structure.
The terms parent, child, and sibling are used to describe the
relationships.
In a node tree, the top node is called the root
Every node, except the root, has exactly one parent node
A node can have any number of children
A leaf is a node with no children
Siblings are nodes with the same parent
<html>
<head>
<title>DOM Tutorial</title> The <html> node has two child nodes;
</head> <head> and <body>
<body> The <head> node has one child node; the
<h1>DOM Lesson one</h1> <title> node
<p>Hello world!</p> The <title> node also has one child node;
</body> the text node "DOM Tutorial"
</html The <h1> and <p> nodes are siblings, and
both child nodes of <body> 63
HTML DOM Properties and Methods
HTML DOM Properties
These are some typical DOM properties:
x.innerHTML - the inner text value of x (a HTML element)
x.nodeName - the name of x
x.nodeValue - the value of x
x.parentNode - the parent node of x
x.childNodes - the child nodes of x
x.attributes - the attributes nodes of x
HTML DOM Methods
x.getElementById(id) - get the element with a specified id
x.getElementsByTagName(name) - get all elements with a
specified tag name
x.appendChild(node) - insert a child node to x
x.removeChild(node) - remove a child node from x
64
innerHTML
is useful for returning or replacing the content of HTML elements
(including <html> and <body>)
<html>
<body>
<script type="text/javascript">
txt=document.getElementById("intro").innerHTML;
document.write("The text from the intro paragraph: " +
txt);
</script>
</body>
</html>
Hello World!
67
getElementsByTagName() Method
<html>
<body>
<p id="intro">Example</p>
<div id="main">
<p id="main1">The DOM is very useful</p>
<p id="main2">This example demonstrates how to use the
<b>getElementsByTagName</b> method</p>
</div>
<script type="text/javascript">
x=document.getElementsByTagName("p");
document.write("First paragraph text: " + x[0].innerHTML);
</script>
</body> Example
</html>
The DOM is very useful
70
Changing the Text HTML Element
The easiest way to get or modify the content of an element is by
using the innerHTML property
<html>
<body>
<p id="p1">Hello World!</p>
<script type="text/javascript">
document.getElementById("p1").innerHTML="New text!";
</script>
<p>The paragraph above was changed by the script.</p>
</body>
</html>
71
Using function
<html>
<head>
<script type="text/javascript">
function ChangeText(){
document.getElementById("p1").innerHTML="New text!";
}
</script>
</head>
<body>
<p id="p1">Hello world!</p>
<input type="button" onclick="ChangeText()" value="Click me
to change text above">
</body>
</html>
72
Using the Style Object
The Style object represents of each HTML element represents
its individual style.
<html>
<head>
<script type="text/javascript">
function ChangeText() {
document.getElementById("p1").style.color="blue";
document.getElementById("p1").style.fontFamily="Arial";
}
</script>
</head>
<body>
<p id="p1">Hello world!</p>
<input type="button" onclick="ChangeText()"
value="Click me to change text above">
</body>
73
</html>
DOM Window Object
Method Description
alert() Displays an alert box with a message and an OK button
blur() Removes focus from the current window
open() Opens a new browser window
close() Closes the current window
createPopup() Creates a pop-up window
focus() Sets focus to the current window
moveBy() Moves a window relative to its current position
moveTo() Moves a window to the specified position
print() Prints the contents of the current window
resizeBy() Resizes a window by the specified pixels
resizeTo() Resizes a window to the specified width and height
scrollBy() Scrolls the content by the specified number of pixels
scrollTo() Scrolls the content to the specified coordinates
74
Open & close
The open() method is used to open a new browser window.
Syntax
window.open(URL,name,specs,replace)
Name -Specifies the target attribute or the name of the window. The
following values are supported:
_blank - URL is loaded into a new window (default)
_parent - URL is loaded into the parent frame
_self - URL replaces the current page
_top - URL replaces any framesets that may be loaded
name - The name of the window
Specs - A comma-separated list of items.
height=pixels - The height of the window. Min. value is 100
width=pixels The width of the window. Min. value is 100
resizable=yes|no|1|0 Whether or not the window is resizable.
menubar=yes|no|1|0 Whether or not to display the menu bar.
scrollbars=yes|no|1|0 Whether or not to display scroll bars.
toolbar=yes|no|1|0 Whether or not to display the browser toolbar.
The close() method is used to close the current window.
Syntax
window.close()
75
Open & close
<html>
<head>
<script type="text/javascript">
function closeWin()
{
myWindow.close()
}
</script>
</head>
<body>
<script type="text/javascript">
myWindow=window.open('','','width=200,height=100')
myWindow.document.write("This is 'myWindow'")
</script>
<input type="button" value="Close 'myWindow'"
onclick="closeWin()" />
</body>
76
</html>
createPopup()
The createPopup() method is used to create a pop-up window.
Syntax
window.createPopup()
<html>
<head>
<script type="text/javascript">
function show_popup()
{
var p=window.createPopup()
var pbody=p.document.body
pbody.style.backgroundColor="lime"
pbody.style.border="solid black 1px"
pbody.innerHTML="This is a pop-up! Click outside to close."
p.show(150,150,200,50,document.body)
}
</script>
</head>
<body>
<button onclick="show_popup()">Create pop-up!</button>
</body> 77
</html>