Lecture 05 JavaScript
Lecture 05 JavaScript
Lecture 05 JavaScript
Javascript
Why use client-side scripting?
• Server side languages already allows us to create
dynamic web pages. Why also use client-side
scripting?
– Client-side scripting (Javascript) benefits:
• Usability: can modify a page without having to
post back to the server (faster UI)
• Efficiency: can make small, quick changes to
page without waiting for server
• Event-driven: can respond to user actions like
clicks and key presses
2
Why use server-side programming?
• Server-side programming (ASP.NET, PHP, etc.)
benefits:
– Security: has access to server's private data;
client can't see source code
– Compatibility: not subject to browser
compatibility issues
– Power: can write files, open connections to
servers, connect to databases, ...
3
What is Javascript?
5
How To Use JavaScript
<script>
<!--
document.getElementById("demo").innerHTML="Hello World!";
//-->
</script>
</body>
</html>
JavaScript in <head>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Using JavaScript in HTML Head</title>
<meta charset="UTF-8">
<script type="text/javascript">
function changeText()
{
document.getElementById("demo").innerHTML="Hello World!";
}
</script>
</head>
<body>
<h1>Using JavaScript in HTML Head</h1>
</body>
</html>
See: Example 02
Using an External JavaScript
function changeText()
{
document.getElementById("demo").innerHTML="Hello World!";
}
Reference: http://stackoverflow.com/questions/436411/where-is-the-best-place-to-put-script-tags-in-html-markup
Using an External JavaScript
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Using External JavaScript</title>
<meta charset="UTF-8">
</head>
<body>
</body>
</html>
See: Example 03
SYNTAX
JavaScript Statements
See: http://www.w3schools.com/js/js_operators.asp
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or
values.
See: http://www.w3schools.com/js/js_operators.asp
JavaScript Comparison Operators
Comparison operators are used in logical statements to determine equality or
difference between variables or values.
Given that x=5, the table below explains the comparison operators:
See: http://www.w3schools.com/js/js_comparisons.asp
JavaScript Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
See: http://www.w3schools.com/js/js_comparisons.asp
If...Else Statements
var d = new Date();
var time = d.getHours();
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>=10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{
document.write("<b>Hello World!</b>");
}
See: http://www.w3schools.com/js/js_if_else.asp
Switch Statement
var d=new Date();
var theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
See: http://www.w3schools.com/js/js_switch.asp
For Loop
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
See: http://www.w3schools.com/js/js_loop_for.asp
While Loop
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
See: http://www.w3schools.com/js/js_loop_while.asp
Do While Loop
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);
See: http://www.w3schools.com/js/js_loop_while.asp
JavaScript Functions
• A function contains code that will be executed by an event or by a call to the
function.
– You may call a function from anywhere within a page (or even from other pages if
the function is embedded in an external .js file).
– Functions can be defined both in the <head> and in the <body> section of a
document. However, to assure that a function is read/loaded by the browser
before it is called, it could be wise to put functions in the <head> section.
• Note: A function with no parameters must include the parentheses () after
the function name.
• Note: The word function must be written in lowercase letters, otherwise a
JavaScript error occurs! Also note function name is case-sensitive.
See: http://www.w3schools.com/js/js_functions.asp
JavaScript Functions
function product(a,b)
{
return a*b;
}
C = product(4,3);
JavaScript Variable Scope
• Variables declared within a JavaScript function, become local to the function.
• A global variable has global scope: All scripts and functions on a web page can
access it.
• If you assign a value to a variable that has not been declared, it will
automatically become a global variable.
</script>
Anonymous Functions
var x = function (a,b) {
return a*b;
};
Anonymous Functions
var x = function (a,b) {
return a*b;
};
var y = x(4,5);
Functions in Expressions
function myFunction(a, b) {
return a * b;
}
var x = myFunction(4, 3) * 2;
Self-Invoking Functions
(function () {
var x = "Hello!!";
})();
JavaScript Popup Boxes
See: http://www.w3schools.com/js/js_popup.asp
JavaScript Popup Boxes
See: http://www.w3schools.com/js/js_popup.asp
JavaScript Popup Boxes
See: http://www.w3schools.com/js/js_popup.asp
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.
Alert Box
See: http://www.w3schools.com/js/js_popup.asp
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.
var r=confirm("Press a button");
if (r==true)
{
alert("You pressed OK!");
}
else
{
alert("You pressed Cancel!");
}
See: http://www.w3schools.com/js/js_popup.asp
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.
var name=prompt("Please enter your name","");
if (name!=null && name!="")
{
document.write("Hello " + name);
}
See: http://www.w3schools.com/js/js_popup.asp
JavaScript Events
See: http://www.w3schools.com/js/js_events.asp
Event Attributes
See: http://www.w3schools.com/jsref/dom_obj_event.asp
Mouse Events
See: http://www.w3schools.com/jsref/dom_obj_event.asp
JAVASCRIPT BUILT IN OBJECTS
STRING OBJECT
JavaScript String Object
Methods:
• charAt() Returns the character at the specified index
• substr() Extracts the characters from a string, beginning at a specified start
position, and through the specified number of character
• toLowerCase() Converts a string to lowercase letters
• toUpperCase() Converts a string to uppercase letters
Property:
– length
See: http://www.w3schools.com/jsref/jsref_obj_string.asp
JavaScript String Object
var txt = "Hello World!";
See: Example 05
JavaScript String Object
For Example:
str="We can have \"double quotes\" in strings";
See: Example 07
JAVASCRIPT BUILT IN OBJECTS
ARRAY OBJECT
JavaScript Array Object
Methods:
• concat() Joins two or more arrays, and returns a copy of the joined arrays
• join() Joins all elements of an array into a string
• reverse() Reverses the order of the elements in an array
• slice() Selects a part of an array, and returns the new array
• sort() Sorts the elements of an array
• toString() Converts an array to a string, and returns the result
JAVASCRIPT BUILT IN OBJECTS
DATE OBJECT
JavaScript Date Object
// date string
var d2 = new Date("October 17, 1979 11:13:00");
Methods:
• getDate() Returns the day of the month (from 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)
• getTime() Returns the number of milliseconds since midnight Jan 1, 1970
JavaScript Date Object
var currentDate = new Date();
var x=Math.PI;
var y=Math.sqrt(16);
Methods:
• abs(x) Returns the absolute value of x
• ceil(x) Returns x, rounded upwards to the nearest
• floor(x) Returns x, rounded downwards to the nearest integer
• max(x,y,z,...,n) Returns the number with the highest value
• min(x,y,z,...,n) Returns the number with the lowest value
• random() Returns a random number between 0 and 1
• round(x) Rounds x to the nearest integer
See: http://www.w3schools.com/jsref/jsref_obj_math.asp
JavaScript Math Object
x=Math.random();
x=Math.floor(x*11);
See: Example 06
Document Object Model (DOM)
See: http://www.w3schools.com/htmldom/
HTML Nodes
<html>
<head>
<title>My title</title>
</head>
<body>
<h1>My header</h1>
<a href="http://fc.riphah.edu.pk">My link</a>
</body>
</html>
DOM Tree Example
Node Parents, Children & Siblings
– Every node, except the root, has exactly one parent node
– nodeName is read-only
– nodeName of an element node is the same as the tag name
– nodeName of an attribute node is the attribute name
– nodeName of a text node is always #text
– nodeName of the document node is always #document
HTML DOM Properties
There are two special document properties that allow access to the tags:
• document.documentElement - returns the root node of the document
• document.body - gives direct access to the <body> tag
The getElementById() Method
<p id="intro">Hello World!</p>
<p>This example demonstrates the <b>getElementById</b> method!</p>
<script>
x=document.getElementById("intro");
document.write("<p>The text from the intro paragraph: " +
x.innerHTML + "</p>");
</script>
See: Example 01
The getElementsByTagName() Method
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<script>
x=document.getElementsByTagName("p");
document.write("Text of second paragraph: " + x[1].innerHTML);
</script>
See: Example 02
DOM Node List Length
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>length</b> property.</p>
<script>
x=document.getElementsByTagName("p");
for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}
</script>
See: Example 03
Change the Text of an HTML Element
document.getElementById("p1").innerHTML="New text!";
Change Style of an HTML Element
document.body.style.backgroundColor="#cccccc";
document.getElementById("p1").style.color="#00cc00";
document.getElementById("p1").style.fontFamily="Arial";
See: http://www.w3schools.com/jsref/dom_obj_style.asp
GLOBAL DOM OBJECTS
Global DOM Objects
• Methods:
– alert, blur, clearInterval, clearTimeout, close, confirm, focus, moveBy, moveTo,
open, print, prompt, resizeBy, resizeTo, scrollBy, scrollTo, setInterval, setTimeout
• Properties:
– document, history, location, name
See: http://www.w3schools.com/jsref/obj_window.asp
The “window” Object
function delayedMessage() {
var myTimer = setTimeout("alert('Booyah!');", 5000);
}
See: Example 04
The “window” Object
<script type="text/javascript">
var myTimer=setInterval("clock()",1000);
function clock()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("clock").value=t;
}
</script>
<button
onclick="window.clearInterval(myTimer)">Stop</button>
See: Example 05
The “navigator” Object
• Information about the web browser application
• Methods:
– javaEnabled()
• Properties:
– appCodeName, appName, appVersion, ,cookieEnabled, geolocation, language,
onLine, platform, product , userAgent
See: http://www.w3schools.com/jsref/obj_navigator.asp
The “navigator” Object
<div id="example"></div>
<script type="text/javascript">
<!--
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
Txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Language: " + navigator.language + "</p>";
txt+= "<p>Online: " + navigator.onLine + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>Product: " + navigator.product + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
document.getElementById("example").innerHTML=txt;
//-->
</script>
See: Example 06
The “navigator.geolocation” Object
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
See: http://www.w3schools.com/jsref/obj_screen.asp
The “screen” Object
See: Example 07
The “history” Object
• List of sites the browser has visited in this window
• Properties:
– length
• Methods:
– back, forward, go
See: http://www.w3schools.com/jsref/obj_history.asp
The “history” Object
<script type="text/javascript">
function goBack()
{
window.history.back()
}
</script>
See: Example 08
The “location” Object
• Represents the URL of the current web page
• Properties:
– host, hostname, href, pathname, port, protocol, search
• Methods:
– assign, reload, replace
See: http://www.w3schools.com/jsref/obj_location.asp
The “location” Object
<script type="text/javascript">
function newDoc()
{
window.location.assign("http://www.w3schools.com")
}
</script>
See: Example 09
The “document” Object
• Represents current HTML page object model
• Properties:
– anchors, body, cookie, domain, forms, images, links, referrer, title, URL
• Methods:
– getElementById, getElementsByName, getElementsByTagName, write, writeln
See: http://www.w3schools.com/jsref/dom_obj_document.asp
EXAMPLE
FORM VALIDATION
Form Validation
– Numeric Field
Form Validation
<script type="text/javascript">
function validateForm()
{
...
}
</script>
See: Example 03
EXAMPLE
CREATE & RETRIEVE “COOKIES”
Create & Retrieve “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.
• A cookie is nothing but a small text file that's stored in your browser. It
contains some data:
– A name-value pair containing the actual data
– An expiry date after which it is no longer valid
– The domain and path of the server it should be sent to
Create & Retrieve “Cookies”
Cookies can be created, read and erased by JavaScript. They are accessible
through the property document.cookie.
document.write(document.cookie);
wpone=test; wptwo=another test
See: Example 01
Create & Retrieve “Cookies”
function setCookie(name, value, days) {
See: Example 02
Minimum Objectives