Javascript Lecture Notes
Javascript Lecture Notes
● NO!
● Java and JavaScript are two completely
different languages in both concept and design!
● Java (developed by Sun Microsystems) is a
powerful and much more complex programming
language - in the same category as C and C++.
What Can JavaScript do?
● JavaScript gives HTML designers a programming tool - HTML authors are
normally not programmers, but JavaScript is a scripting language with a very
simple syntax! Almost anyone can put small "snippets" of code into their
HTML pages
● JavaScript can react to events - A JavaScript can be set to execute when
something happens, like when a page has finished loading or when a user
clicks on an HTML element
● JavaScript can read and write HTML elements - A JavaScript can read and
change the content of an HTML element
● JavaScript can be used to validate data - A JavaScript can be used to
validate form data before it is submitted to a server. This saves the server
from extra processing
● JavaScript can be used to detect the visitor's browser - A JavaScript can be
used to detect the visitor's browser, and - depending on the browser - load
another page specifically designed for that browser
● JavaScript can be used to create cookies - A JavaScript can be used to store
and retrieve information on the visitor's computer
JavaScript = ECMAScript
JavaScript is an implementation of the ECMAScript
language standard. ECMA-262 is the official
JavaScript standard.
JavaScript was invented by Brendan Eich at
Netscape (with Navigator 2.0), and has appeared in
all browsers since 1996.
The official standardization was adopted by the
ECMA organization (an industry standardization
association) in 1997.
The ECMA standard (called ECMAScript-262) was
approved as an international ISO (ISO/IEC 16262)
standard in 1998.
The development is still in progress.
JavaScript Syntax:
A JavaScript consists of JavaScript statements that are
placed within the <script>... </script>
HTML tags in a web page.
You can place the <script> tag containing your
JavaScript anywhere within you web page but it
is preferred way to keep it within the <head> tags.
The <script> tag alert the browser program to begin
interpreting all the text between these
tags as a script. So simple syntax of your JavaScript will
be as follows
<script ...>
JavaScript code
</script>
Hello World!
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
Because you can use spaces, tabs, and newlines freely in your program so you are
free to format and indent your programs in a neat and consistent way that makes
the code easy to read and understand.
Semicolons are Optional:
Simple statements in JavaScript are generally followed by a semicolon character,
just as they are in C, C++, and Java. JavaScript, however, allows you to omit this
semicolon if your statements are each placed on a separate line. For example, the
following code could be written
without semicolons
<script language="javascript" type="text/javascript">
var2 = 20
</script>
But when formatted in a single line as follows, the semicolons are required:
Case Sensitivity:
Array indexes are zero-based, which means the first item is [0],
second is [1], and so on.
JavaScript Objects
After the execution of the statements above, the variable x will hold the value 5,
and carname will hold the value Volvo.
Note: When you assign a text value to a variable, use quotes around the value.
Note: If you redeclare a JavaScript variable, it will not lose its value
JavaScript Reserved Words or Key Words
The following are reserved words in JavaScript. They cannot be used as
JavaScript variables, functions, methods, loop labels, or any object names.
+ Addition x=y+2 7 5
- Subtraction x=y-2 3 5
* Multiplication x=y*2 10 5
x=++y 6 6
++ Increment
x=y++ 5 6
x=--y 4 4
-- Decrement
x=y-- 5 4
JavaScript Assignment Operators
Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment operators:
= x=y x=5
%= x%=y x=x%y
The + Operator Used on Strings
Example
txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2;
The result of txt3 will be:
What a very nice day
or insert a space into the expression:
Example
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
Example
x=5+5;
y="5"+5;
z="Hello"+5;
x==8 false
== equal to
x==5 true
x==="5" false
=== exactly equal to (equal value and equal type)
x===5 true
x!=="5" true
!== not equal (different value or different type)
x!==5 false
●switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
Looping
● If we want to repeat several identical
conditional statements one after another,
JavaScript provides you with four looping
statements-while, do while, for, and for in.
While Loop
● while loops runs over and over until its expression returns
false.
● Syntax of while Statement:
while (expression){
Statement(s) to be executed if expression is true
}
● The expression written in while statement is evaluated at
entry level and expression is evaluated. If the value of
expression is true the statements inside the loop are
executed. If the condition is false initially the statements
written inside loop are not executed even once. If the
expression is true the statements inside loop are executed
repeatedly until the condition become false.
Example
var i=1;
While(i<=10)
{
[Link](i,”</br>);
i=i+1;
}
Output will be
1
2
…
10
Do While Loop
● Do while loops runs over and over until its expression
returns false.
● Syntax of do while Statement:
do{
Statement(s) to be executed;
} while (expression);
while (expression){
Statement(s) to be executed if expression is true
}
● In do while loop statements written inside the loop are
executed once and then expression is evaluated at exit of
loop .So even if the expression is false loop statements are
executed at least once.
Example
var i=1;
do
{
[Link](i,”</br>);
i=i+1;
}
while(i>10)
Output will be
1
For Loop
●for loop is frequently used to execute code a
certain number of times.
●The for loop is the most compact form of looping and includes the
following three important parts:
The loop initialization where we initialize our counter to a starting
value. The initialization statement is executed before the loop
begins.
The test statement which will test if the given condition is true or
not. If condition is true then code given inside the loop will be
executed otherwise loop will come out.
The iteration statement where you can increase or decrease your
counter.
You can put all the three parts in a single line separated by a
semicolon.
Syntax of for loop
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true
}
Example
for(i=1;i<=10;i++)
[Link](i,”</br>”);
Output will be
1
2
..
10
The break Statement:
●The break statement is used to exit a loop early, breaking out of the
enclosing curly braces.
Example
for(i=1;i<=10;i++)
{
If(i==5)
break;
[Link](i,”</br>”);
}
Output will be
1
2
3
4
The continue Statement:
● The continue statement tells the interpreter to
immediately start the next iteration of the loop
and skip remaining code block.
● When a continue statement is encountered,
program flow will move to the loop check
expression immediately and if condition remain
true then it start next iteration otherwise control
comes out of the loop.
Example
for(i=1;i<=10;i++)
{
If (i==5)
{
continue
}
[Link](i,”</br>”);
}
Output will be
1
2
3
4
6
…
10
Arrays in JavaScript
● Arrays is a set of variables with the same name or a
special variable which can hold more than one value at
a [Link] use arrays when we want to work with a
certain block of data.
Example
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!
An array can hold many values under a single name, and you can access
the values by referring to an index number.
Create an Array
Property Description
Returns the function that
constructor created the Array
Sets or returns the
length object's
number prototype
Allows youelements
of to add in
prototype an array and methods
properties
to an Array object
Array Object Methods
Method Description
Joins two or more arrays, and returns
concat()
a copy of
Search thethe joined
array arrays
for an element and
indexOf()
returns
Joins allits position of an array into a
elements
join() Search
string the array for an element,
lastIndexOf() starting at the end, and returns its
Removes
position the last element of an array,
pop()
and returns that element
Array Object Methods
Adds new elements to the end of
push() Reverses the order of the elements
reverse() Removes thereturns
an array, and first element
the newof length
an
shift() in an array
array,
Selectsand returns
a part that
of an element
array, and
slice()
returns the new array
sort() Sorts the elements of an array
Adds/Removes elements from an
splice()
array
Converts an array to a string, and
toString()
returns
Adds theelements
new result to the
unshift() beginning of an array, and
Returns thenew
returns the primitive
lengthvalue of an
valueOf()
array
Examples of using array methods
<html>
<body>
<script>
function myFunction()
{
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = [Link](stale);
var x=[Link]("demo");
[Link]=children;
}
</script>
</body>
</html>
Some Other Examples
Add a new item to an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("Kiwi")
● The result of fruits will be:
Banana,Orange,Apple,Mango,Kiwi
Reverse the order of the elements in an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();
● Example
● Select elements from an array:
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = [Link](1,3)
The result of citrus will be:
Orange,Lemon
Example
Sort an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();
The result of fruits will be:
Apple,Banana,Mango,Orange
Function
A JavaScript function is a collection of statements,
either named or unnamed (anonymous),that can
be called from elsewhere within a JavaScript
program. Functions can accept arguments,
which are input values passed into the function.
Within a function, those arguments
passed into the function can be acted upon and
the results returned to the caller of the
functionvia a return value
Functions are perfect when you have something
that needs to happen multiple times within
a program. Rather than defining the same code
multiple times, you can use a function (which is
really just like a mini program inside a program)
to perform that action.
JavaScript Function Syntax
A function is written as a code block (inside curly { }
braces), preceded by the function keyword:
function functionname()
{
some code to be executed
}
The code inside the function will be executed when
"someone" calls the function.
The function can be called directly when an event
occurs (like when a user clicks a button), and it can be
called from "anywhere" by JavaScript code.
Calling a Function with Arguments
When you call a function, you can pass along some
values to it, these values are called arguments or
parameters.
These arguments can be used inside the
[Link] can send as many arguments as
you like, separated by commas (,)
myFunction(argument1,argument2)
Declare the argument, as variables, when you
declare the function:
function myFunction(var1,var2)
{
some code
}
The variables and the arguments must be in the
expected order. The first variable is given the
value of the first passed argument etc.
Example
<html>
<head>
<script>
function myFunction(name,job)
{
[Link]("Welcome " + name + ", the " + job);}
myFunction("Mukesh","Manager")
</script>
</head>
</html>
Output
Welcome Mukesh, the Manager
Functions With a Return Value
Sometimes you want your function to return a value back to
where the call was made.
This is possible by using the return statement.
When using the return statement, the function will stop
executing, and return the specified value.
Example
Calculate the product of two numbers, and return the result:
function myFunction(a,b)
{
return a*b;
}
Complete Example
<html>
<head>
<script>
function myFunction(a,b)
{
return a*b;
}
c=myFunction(2,3)
[Link]("multiplicationis",c);
</script>
</head>
</html>
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 of 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 a variable that has not yet
been declared, the variable will automatically be
declared as a GLOBAL variable.
This statement:
carname="Volvo";
will declare the variable carname as a global
variable , even if it is executed inside a function.
JavaScript Objects
● Almost everything in JavaScript can be an
Object: Strings, Functions, Arrays, Dates....
● Objects are just data, with properties and
methods.
Properties and Methods
● Properties are values associated with objects.
● Methods are actions that objects can perform
A Real Life Object. A Car:
<script>
txt=[Link]("intro").innerHTML;
txt1=[Link]("intro1").innerHTML;
[Link](txt);
[Link]("<br>");
[Link](txt1);
</script>
</body>
</html>
Output
Hello World!
Thank You
Hello World!
Thank You
In the example above, getElementById is a method,
while innerHTML is a property.
The getElementById Method
<p>Click the "Try it" button to return the value of each element in the
form.</p>
<p id="demo"></p>
</body>
</html>
● First name:
Last name:
Click the "Try it" button to return the value of
each element in the form.
● Donald
Duck
Submit
● Try it
● The following HTML object collections are
accesible:
[Link]
[Link]
[Link]
[Link]
●
JavaScript HTML DOM - Changing
HTML
● The HTML DOM allows JavaScript to change the
content of HTML elements.
Changing the HTML Output Stream
JavaScript can create dynamic HTML content:
Date: Wed Mar 26 21:48:02 2014
In JavaScript, [Link]() can be used to
write directly to the HTML output stream:
Example
<html>
<body>
<script>
[Link](Date());
</script>
</body>
</html>
Output
Wed Mar 26 21:51:16 2014
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:
[Link](id).innerHTML=new
HTML
Example
<html>
<body>
<p id="p1">Hello World!</p>
<script>
[Link]("p1").innerHTML="New
text!";
</script>
</body>
</html>
Output
New text!
The paragraph above was changed by a script.
This example changes the content of an <h1> element:
<html>
<body>
<h1 id="header">Old Header</h1>
<script>
var element=[Link]("header");
[Link]="New Header";
</script>
<p>"Old Header" was changed to "New Header"</p>
</body>
</html>
Output
New Header
"Old Header" was changed to "New Header"
Example explained:
● The HTML document above contains an <h1>
element with id="header"
● We use the HTML DOM to get the element with
id="header"
● A JavaScript changes the content (innerHTML)
of that element
Changing the Value of an Attribute
● To change the value of an HTML attribute, use
this syntax:
[Link](id).attribute=new value
This example changes the value of the src attribute
of an <img> element:
<html>
<body>
<img id="image" src="[Link]" width="160"
height="120">
<script>
[Link]("image").src="[Link];
</script>
<p>The original image was [Link], but the script
changed it to [Link]</p>
</body>
</html>
Output
● <script>
● [Link]("p2").[Link]="blue";
● [Link]("p2").[Link]="Arial";
● [Link]("p2").[Link]="larger";
● </script>
● </body>
● </html>
Output
● Hello World!
● Hello World!
● The paragraph above was changed by a script.
Using Events
● The HTML DOM allows you to execute code
when an event occurs.
● Events are generated by the browser when
"things happen" to HTML elements
●An element is clicked on
●The page has loaded
●Input fields are changed
Example
● This example changes the style of the HTML element with
id="id1", when the user clicks a button:
<html>
<body>
</body>
</html>
Example –To make an element
invisible
<html>
<body>
<p id="p1">
This is a text.
This is a text.
This is a text.
This is a text.
</p>
</body>
</html>
HTML DOM Style Object
● Style object
● The Style object represents an individual style
statement.
● The Style object can be accessed from the
document or from the elements to which that
style is applied.
● Syntax for using the Style object properties:
● [Link]("id").[Link]="v
alue"
JavaScript HTML DOM Events
● HTML DOM allows JavaScript to react to HTML
events.
Reacting to 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:
onclick=JavaScript
Examples of HTML events:
● 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
Examples
● In this example, the content of the <h1> element
is changed when a user clicks on it:
<html>
<body>
<h1 onclick="[Link]='Ooops!'">Click on
this text!</h1>
</body>
</html>
●In this example, a function is called from the event handler:
<html>
<head>
<script>
function changetext(id)
{
[Link]="Ooops!";
}
</script>
</head>
<body>
<h1 onclick="changetext(this)">Click on this text!</h1>
</body>
</html>
HTML Event Attributes
To assign events to HTML elements you can use event attributes.
Example
Assign an onclick event to a button element:
<!DOCTYPE html>
<html>
<body>
<script>
function displayDate()
{
[Link]("demo").innerHTML=Date();
}
</script>
<p id="demo"></p>
</body>
</html>
Assign Events Using the HTML DOM
● The HTML DOM allows you to assign events to HTML elements using JavaScript:
● Example
Assign an onclick event to a button element:
● Example
<html>
<body>
<script>
function displayDate()
{
[Link]("demo").innerHTML=Date();
}
</script>
<p id="demo"></p>
</body>
</html>
● In the example above, a function named
displayDate is assigned to an HTML element
with the id="myBtn".
● The function will be executed when the button is
clicked.
The onchange event are often used in combination with validation of input fields.
The onchange Event
Below is an example of how to use the onchange. The upperCase() function will
be called when a user changes the content of an input field.
<html>
<head>
<script>
function myFunction()
{
var x=[Link]("fname");
[Link]=[Link]();
}
</script>
</head>
<body>
</body>
</html>
<html>
<head>
<script>
function myFunction()
{
var x=[Link]("fname");
[Link]=[Link]();
}
</script>
</head>
<body>
</body>
</html>
The onmouseover and onmouseout
Events
● The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an HTML element.
● <html>
● <body>
● <script>
● function mOver(obj)
● {
● [Link]="Thank You"
● }
● function mOut(obj)
● {
● [Link]="Mouse Over Me"
● }
● </script>
● </body>
● </html>
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
● <html>
● <body>
● <script>
● function mDown(obj)
● {
● [Link]="#1ec5e5";
● [Link]="Release Me"
● }
● function mUp(obj)
● {
● [Link]="#D94A38";
● [Link]="Thank You"
● }
● </script>
● </body>
● </html>
HTML DOM Events
● HTML DOM Events
● HTML DOM events allow JavaScript to register
different event handlers on elements in an HTML
document.
● Events are normally used in combination with
functions, and the function will not be executed
before the event occurs (such as when a user
clicks a button).
Mouse Events
Property
Property Description
onclick The event occurs when the user clicks on an element
The event occurs when the user double-clicks on an
ondblclick
element
The event occurs when a user presses a mouse button
onmousedown
over an element
The event occurs when the pointer is moving while it is
onmousemove
over an element
The event occurs when the pointer is moved onto an
onmouseover
element
The event occurs when a user moves the mouse
onmouseout
pointer outoccurs
The event of an element
when a user releases a mouse button
onmouseup
over an element
Keyboard Events
Attribute Description
The event occurs
onkeydown when the user
The event is
occurs
onkeypress pressing
when theauser
key
The event occurs
onkeyup presses
when thea user
key
releases a key
Frame/Object Events
Attribute
The event occurs when an image is
onabort stopped from loading before completely
loaded (for <object>)
<p>When you leave the input field, a function is triggered which transforms the input text to upper
case.</p>
</body>
</html>
On change
● <html>
● <head>
● <script>
● function myFunction()
●{
● var x=[Link]("fname");
● [Link]=[Link]();
●}
● </script>
● </head>
● <body>
● </body>
● </html>
on select
● <!DOCTYPE html>
● <html>
● <head>
● <script>
● function myFunction()
●{
● alert("You have selected some text!");
●}
● </script>
● </head>
● <body>
● </body>
● </html>
JavaScript Window - The Browser
Object Model
● The Browser Object Model (BOM) allows
JavaScript to "talk to" the browser.
The Browser Object Model (BOM)
● There are no official standards for the Browser
Object Model (BOM).
● Since modern browsers have implemented
(almost) the same methods and properties for
JavaScript interactivity, it is often referred to, as
methods and properties of the BOM.
The Window Object
● The window object is supported by all browsers.
It represent the browser's 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:
[Link]("header");
is the same as:
[Link]("header");
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:
●[Link] - the inner height of the browser window
●[Link] - the inner width of the browser window
● For Internet Explorer 8, 7, 6, 5:
[Link]
[Link]
● or
[Link]
[Link]
A practical JavaScript solution
(covering all browsers):
<html>
<body>
<p id="demo"></p>
<script>
var w=[Link]
|| [Link]
|| [Link];
var h=[Link]
|| [Link]
|| [Link];
x=[Link]("demo");
[Link]="Browser inner window width: " + w + ", height: " + h + "."
</script>
</body>
</html>
Other Window Methods
● [Link]() - open a new window
● [Link]() - close the current window
● [Link]() -move the current window
● [Link]() -resize the current window
JavaScript Window Screen
The [Link] object contains information
about the user's screen.
● Window Screen
● The [Link] object can be written
without the window prefix.
● Some properties:
● [Link] - available screen width
● [Link] - available screen height
● Window Screen Available Width
● The [Link] property returns the width
of the visitor's screen, in pixels, minus interface
features like the Windows Taskbar.
● Window Screen Available Height
● The [Link] property returns the
height of the visitor's screen, in pixels, minus
interface features like the Windows Taskbar.
All ScreenProperties
<html>
<body>
<p id="demo"></p>
<script>
var w=[Link]
|| [Link]
|| [Link];
var h=[Link]
|| [Link]
|| [Link];
x=[Link]("demo");
[Link]="Browser inner window width: " + w + ", height: " + h + "."
</script>
</body>
</html>
JavaScript Window Location
●The [Link] object can be used to get the current page
address (URL) and to redirect the browser to a new page.
●Window Location
●The [Link] object can be written without the window
prefix.
Some examples:
●[Link] returns the domain name of the web host
●[Link] returns the path and filename of the current
page
●[Link] returns the port of the web host (80 or 443)
●[Link] returns the web protocol used (http:// or [Link]
Window Location Href
● The [Link] property returns the URL of the
current page.
Example
Return the entire URL (of the current page):
<script>
[Link]([Link]);
</script>
The output of the code above is:
[Link]
Window Location Pathname
● The [Link] property returns the path
name of a URL.
Example
Return the path name of the current URL:
<script>
[Link]([Link]);
</script>
The output of the code above is:
/js/js_window_location.asp
Window Location Assign
The [Link]() method loads a new document.
<html>
<head>
<script>
function newDoc()
{
[Link]("[Link]
}
</script>
</head>
<body>
</body>
</html>
JavaScript Window History
● The [Link] object contains the browsers
history.
Window History
● The [Link] object can be written without the
window prefix.
● To protect the privacy of the users, there are
limitations to how JavaScript can access this object.
Some methods:
● [Link]() - same as clicking back in the browser
● [Link]() - same as clicking forward in the
browser
Window History Back
● The [Link]() method loads the previous URL in the history list.
● This is the same as clicking the Back button in the browser.
● Example
● Create a back button on a page:
<html>
<head>
<script>
function goBack()
{
[Link]()
}
</script>
</head>
<body>
</body>
</html>
Window History Forward
● The history forward() method loads the next URL in the history list.
● This is the same as clicking the Forward button in the browser.
Example
Create a forward button on a page:
<html>
<head>
<script>
function goForward()
{
[Link]()
}
</script>
</head>
<body>
</body>
</html>
JavaScript Window Navigator
● The [Link] object contains
information about the visitor's browser.
● Window Navigator
● The [Link] object can be written
without the window prefix.
● Example
● <div id="example"></div>
<script>
[Link]("example").innerHTML=txt;
</script>
Output
Browser CodeName: Mozilla
Browser Name: Microsoft Internet Explorer
Browser Version: 4.0 (compatible; MSIE 8.0; Windows NT 6.1;
WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR
3.5.30729; .NET CLR 3.0.30729; InfoPath.2)
Cookies Enabled: true
Browser Language: undefined
Browser Online: true
Platform: Win32
User-agent header: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT
6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR
3.5.30729; .NET CLR 3.0.30729; InfoPath.2)
User-agent language: en-us
● 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
Browser Detection
● Since the navigator object can be misleading
about browser detection, using object detection
can be used to sniff out different browsers.
● Since different browsers support different
objects, you can use objects to detect browsers.
For example, since only Opera supports the
property "[Link]", you can use that to
identify Opera.
● Example: if ([Link]) {...some action...}
JavaScript 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
● [Link]("sometext");
The [Link] method can be written without the
window prefix.
Example
<html>
<body>
<script>
function myFunction()
{
alert("I am an alert box!");
}
</script>
</body>
</html>
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
● [Link]firm("sometext");
● The [Link]firm() method can be written
without the window prefix.
Example
<html>
<body>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var r=confirm("Press a button!");
if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}
[Link]("demo").innerHTML=x;
}
</script>
</body>
</html>
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
[Link]("sometext","defaultText");
The [Link]() method can be written without the
window prefix.
var person=prompt("Please enter your name","Harry
Potter");
if (person!=null)
{
x="Hello " + person + "! How are you today?";
[Link]("demo").innerHTML=x;
}
Line Breaks
● To display line breaks inside a popup box, use a back-slash followed by the character n.
<html>
<body>
<script>
function myFunction()
{
alert("Hello\nHow are you?");
}
</script>
</body>
</html>
JavaScript Cookies
●Cookies let you store user information in web pages.
What are Cookies?
Cookies are data, stored in small text files, on your computer.
When a web server has sent a web page to a browser, the connection is
shut down, and the server forgets everything about the user.
Cookies were invented to solve the problem "how to remember information
about the user":
When a user visits a web page, his name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his name.
Cookies are saved in name-value pairs like:
username=John Doe
When a browser request a web page from a server, cookies belonging to
the page is added to the request. This way the server gets the necessary
data to "remember" information about users.
Create a Cookie with JavaScript
● JavaScript can create cookies, read cookies, and delete
cookies with the property [Link].
● With JavaScript, a cookie can be created like this:
● [Link]="username=John Doe";
● You can also add an expiry date (in UTC or GMT time). By
default, the cookie is deleted when the browser is closed:
● [Link]="username=John Doe; expires=Thu, 18
Dec 2013 12:00:00 GMT";
● With a path parameter, you can tell the browser what path
the cookie belongs to. By default, the cookie belongs to the
current page.
● [Link]="username=John Doe; expires=Thu, 18
Dec 2013 12:00:00 GMT; path=/";
Read a Cookie with JavaScript
● Read a Cookie with JavaScript
● With JavaScript, cookies can be read like this:
● var x = [Link];
●
[Link] will return all cookies in one
string much like: cookie1=value; cookie2=value;
cookie3=value;
Change a Cookie with JavaScript
● Change a Cookie with JavaScript
● With JavaScript, you can change a cookie the
same way as you create it:
● [Link]="username=John Smith;
expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";
● The old cookie is overwritten.
Delete a Cookie with JavaScript
● Delete a Cookie with JavaScript
● Deleting a cookie is very simple. Just set the
expires parameter to a passed date:
● [Link] = "username=; expires=Thu, 01
Jan 1970 00:00:00 GMT";
● Note that you don't have to specify a cookie
value when you delete a cookie.
The Cookie String
● The [Link] property look like a
normal text string. But is it not.
● Even if you write a whole cookie string to
[Link], when you read it out again,
you can only see the name-value pair of it.
● If you set a new cookie, older cookies are not
overwritten. The new cookie is added to
[Link], so if you read
[Link] again you will get something
like:
● cookie1=value; cookie2=value;
Delete a Cookie with JavaScript
●Deleting a cookie is very simple. Just set the expires parameter to a
passed date:
●[Link] = "username=; expires=Thu, 01 Jan 1970 00:00:00
GMT";
JavaScript Cookie Example
●In the example to follow, we will create a cookie that stores the name of a
visitor.
●The first time a visitor arrives to the web page, he will be asked to fill in his
name. The name is then stored in a cookie.
●The next time the visitor arrives at the same page, he will get a welcome
message.
●For the example we will create 3 JavaScript functions:
●A function to set a cookie value
●A function to get a cookie value
●A function to check a cookie value
A Function to Set a Cookie
First, we create a function that stores the name of the visitor in a
cookie variable:
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
[Link]([Link]()+(exdays*24*60*60*1000));
var expires = "expires="+[Link]();
[Link] = cname + "=" + cvalue + "; " + expires;
}
Example explained:
The parameters of the function above are the name of the cookie
(cname), the value of the cookie (cvalue), and the number of days
until the cookie should expire (exdays).
The function sets a cookie by adding together the cookiename, the
cookie value, and the expires string.
A Function to Get a Cookie
● Then, we create a function that returns the value of a specified cookie:
● function getCookie(cname)
{
var name = cname + "=";
var ca = [Link](';');
for(var i=0; i<[Link]; i++)
{
var c = ca[i].trim();
if ([Link](name)==0) return [Link]([Link],[Link]);
}
return "";
}
● Function explained:
● Take the cookiename as parameter (cname).
● Create a variable (name) with the text to search for (cname + "=").
● Split [Link] on semicolons into an array called ca (ca = [Link](';')).
● Loop through the ca array (i=0;i<[Link];i++), and read out each value trimmed (c=ca[i].trim()).
● If the cookie is found ([Link](name) == 0), return the value of the cookie
([Link]([Link],[Link]).
● If the cookie is not found, return "".
A Function to Check a Cookie
● Last, we create the function that checks if a cookie is set.
● If the cookie is set it will display a greeting.
● If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores
the username cookie for 365 days, by calling the setCookie function:
● function checkCookie()
{
var username=getCookie("username");
if (username!="")
{
alert("Welcome again " + username);
}
else
{
username = prompt("Please enter your name:","");
if (username!="" && username!=null)
{
setCookie("username",username,365);
}
}
}
A Function to Check a Cookie
Last, we create the function that checks if a cookie is set.
If the cookie is set it will display a greeting.
If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the
username cookie for 365 days, by calling the setCookie function:
function checkCookie()
{
var username=getCookie("username");
if (username!="")
{
alert("Welcome again " + username);
}
else
{
username = prompt("Please enter your name:","");
if (username!="" && username!=null)
{
setCookie("username",username,365);
}
}
}
JavaScript Errors - Throw and Try to
Catch
● The try statement lets you 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
}
● <html>
<head>
<script>
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + [Link] + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()">
</body>
</html>
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.
● Syntax
throw exception
The exception can be a JavaScript String, a
Number, a Boolean or an Object.
● Example
● This example examines the value of an input variable. If the value is wrong, an exception (error) is thrown. The error is caught by the
catch statement and a custom error message is displayed:
● Example
● <script>
function myFunction()
{
var y=[Link]("mess");
[Link]="";
try
{
var x=[Link]("demo").value;
if(x=="") throw "empty";
if(isNaN(x)) throw "not a number";
if(x>10) throw "too high";
if(x<5) throw "too low";
}
catch(err)
{
[Link]="Error: " + err + ".";
}
}
</script>
<h1>My First JavaScript</h1>
<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 Maths
● The Math object allows you to perform mathematical tasks on numbers.
Math Object Properties
Property Description
E Returns Euler's number (approx. 2.718)
Returns the natural logarithm of 2
LN2
(approx. 0.693)
Returns the natural logarithm of 10
LN10
(approx. 2.302)
Returns the base-2 logarithm of E
LOG2E
(approx. 1.442)
Returns the base-10 logarithm of E
LOG10E
(approx. 0.434)
PI Returns PI (approx. 3.14)
Returns the square root of 1/2 (approx.
SQRT1_2
0.707)
Returns the square root of 2 (approx.
SQRT2
1.414)
Math Object Methods
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns
Returns the
the arcsine of x,ofinxradians
arctangent as a
atan(x) numeric value between -PI/2 and PI/2
Returns
radians the arctangent of the quotient
atan2(y,x)
of its arguments
Returns x, rounded upwards to the
ceil(x)
nearest integer
cos(x) Returns the cosine of x (x is in radians)
x
exp(x) Returns the value of E
Returns x, rounded downwards to the
floor(x)
nearest
Returns integer
the natural logarithm (base E)
log(x)
of x
Returns the number with the highest
max(x,y,z,...,n)
value
Returns the number with the lowest
min(x,y,z,...,n)
value
Returns the value of x to the power of
pow(x,y)
yReturns a random number between 0
random()
and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
JavaScript Date Object
● The Date object is used to work with dates and
times.
● Date objects are created with new Date().
● There are four ways of instantiating a date:
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes,
seconds, milliseconds);
Date Object Properties
Property Description
Returns the function that created the
constructor
Date object's
Allows you to prototype
add properties and
prototype
methods to an object
Date Object Methods
Method Description
Returns the day of the month (from
getDate()
1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits)
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
Returns the number of milliseconds
getTime()
since midnight Jan 1, 1970
JavaScript Global
● The JavaScript global properties and functions
can be used with all the built-in JavaScript
objects.
● JavaScript Global Properties
Property Description
A numeric value that
Infinity represents positive/negative
NaN infinity
"Not-a-Number" value
Indicates that a variable has
undefined
not been assigned a value
JavaScript Global Functions
Number() Converts an object's value to a number
Parses a string and returns a floating
parseFloat()
point number
parseInt() Parses a string and returns an integer
String() Converts an object's value to a string
HTML DOM Form Object
● Form Object
● The Form object represents an HTML <form>
element.
● Access a Form Object
● You can access a <form> element by using
getElementById():
● var x = [Link]("myForm");
● Create a Form Object
● You can create a <form> element by using the
[Link]() method:
● var x = [Link]("myForm");
● Create a Form Object
● You can create a <form> element by using the
[Link]() method:
● var x = [Link]("myForm");
Form Object Properties
Property Description
Sets or returns the value of the accept-
acceptCharset
charset attribute
Sets or returns invalue
the a formof the action
action
attribute in a form
Sets or returns the value of the
autocomplete
autocomplete attribute in a form
encoding Alias of enctype
Sets or returns the value of the
enctype
enctype attribute
Returns the numberin aofform
elements in a
length
form
Sets or returns the value of the
method
method attribute
Sets or returns theinvalue
a form
of the name
name Sets or returns whether the form-data
attribute in a form
noValidate should be validated or not, on
Sets or returns the value of the target
submission
target
attribute in a form
Form Object Methods
Method Description
reset() Resets a form
submit()