Web Systems and Technologies: Chapter 04. Java Script

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 67

Web Systems and

Technologies
Chapter 04. Java Script
Content
 What is JavaScript
 The Foundation of JavaScript Syntax
 The Core language Objects in JavaScript
 Document Object Model (DOM) and The Browser Objects in JavaScript

2
The Foundation of JavaScript Syntax

3
What is JavaScript
 It is a scripting language that can be used to create client-side scripts and
server-side scripts.
 JavaScript makes it easier to create dynamic and interactive Web pages.
 JavaScript is a scripting language developed by Sun Microsystems and
Netscape.
 JavaScript developed from Netscapes’s Livescript.
 Client applications run in a browser such as Netscape
Navigator, Google Chrome, FireFox or Internet Explorer.

4
JavaScript Advantages
 JavaScript allows interactivity such as:
 Implementing form validation
 React to user actions, e.g. handle keys
 Changing an image on moving mouse over it
 Sections of a page appearing and disappearing
 Content loading and changing dynamically
 Performing complex calculations
 Custom HTML controls, e.g. scrollable table
 Implementing AJAX functionality

5
What Can JavaScript Do?
 Can handle events
 Can read and write HTML elements and modify the DOM tree
 Can validate form data
 Can access / modify browser cookies
 Can detect the user’s browser and OS
 Can be used as object-oriented language
 Can handle exceptions
 Can perform asynchronous server calls (AJAX)

6
Embedding JavaScript in Web Page
 The JavaScript can be inserted into an HTML document in the following ways :
 Using SCRIPT tag:
<script language="JavaScript">
<!--
JavaScript statements;
//-->
</script>
 Using an external File
<script language="JavaScript“ src="filename.js">
</script>
 Using JavaScript Expressions within HTML Tag Attribute Values
 Using JavaScript in event handlers

7
JS Variables
 A variable is a container that refers to a memory location.
 It is used to hold values that may change while the script is executing.
 Variables follow some naming conventions.
 A variable is declared using the keyword ‘var’.
eg. var A = 10;
 Variables have a scope that is determined by where they are declared in the
script.
 Global Variable
 Local Variable
 Literals are fixed values that can be used in the script.

8
JS Variables (1)
 String type – string of characters
var myName = "You can use both single or double quotes for
strings";
 Arrays

var my_array = [1, 5.3, "aaa"];

 Associative arrays (hash tables)


var my_hash = {a:2, b:3, c:"text"};

9
JS Data Types
 JavaScript has a relatively small set of data types.
 Numbers
 Logical or Boolean
 Strings
 Null
 JavaScript is case-sensitive.
 In JavaScript, two variables of different types can be combined.
example: A = “ This apple costs Rs.” + 5
will result in a string with the value "This apple costs Rs. 5".

10
JS Data Type - Example
<HTML>
<HEAD>
<SCRIPT LANGUAGE = "Javascript">
var A = "12" + 7.5;
document.write(A);
</SCRIPT>
</HEAD>
</HTML>

11
JS Literal - Types
 Integer – These can be expressed in decimal, hexadecimal and binary number
system.

 Floating- point - These number can have a decimal point or an “e” or “”E”
followed by an integer.

 String - A string literal is zero or more characters enclosed in single or double


quotation marks.

 Boolean - This can take only two values: True or False.

 null - The null type has only one value: null. Null implies no data.

12
Operators
 Operators take one or more variables or values (operands) and return a new
value.
 JavaScript uses both binary and unary operators.
 Operators are classified depending on the relation they perform like:
 Arithmetic Operator: +, -, *, /, ++, --
 Comparison Operator: ==, !=, >, >=, <, <=
 Logical Operator: &&, ||, !
 String Operator
 Evaluation Operator
 Operator Precedence

13
Evaluation Operator
 These operators generally includes:
 Conditional operator
(condition) ? trueVal : falseVal

Assigns a specified value to a variable if a condition is true, otherwise assigns


an alternate value if condition is false.
eg. status = (age >= 18) ? "adult" : "minor"

 Typeof operator
The typeof operator returns a string indicating the type of the operand.
eg. var x = 5;
document.write(typeof(x));

14
Switch Statement
 The switch statement works like in C#:
switch (variable) { switch-statements.html
case 1:
// do something
break;
case 'a':
// do something else
break;
case 3.14:
// another code
break;
default:
// something completely different
}
15
Loop
 Structures that control repetition in a program are known as loops.

 The various types of loops include:


 For
 Do …. While var counter;
 While for (counter=0; counter<4; counter++) {
alert(counter);
 Break & continue
}
 For….in while (counter < 5) {
 with alert(++counter);
}

16
Function
 JavaScript has several pre-defined functions that we can use within the script.
 Some of pre-defined JavaScript functions includes:
 eval function
 isNaN funtion
 Creating User Defined Functions
function funcName(argument1,argument2,etc)
{ statements; }
 Calling a Function
 Return Statement

17
Function (1)
 Code structure – splitting code into parts
Parameters come in
 Data comes in, processed, result returned
here.

function average(a, b, c) Declaring variables is


{ optional. Type is never
var total; declared.
total = a+b+c;
return total/3;
}
Value returned here.

18
Function Arguments and Return Value
 Functions are not required to return a value
 When calling function it is not obligatory to specify all of its arguments
 The function has access to all the arguments passed via arguments array

function sum() {
var sum = 0;
for (var i = 0; i < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4));
19
Standard Popup Boxes
 Alert box with text and [OK] button
 Just a message shown in a dialog box:
alert("Some text here");
 Confirmation box
 Contains text, [OK] button and [Cancel] button:
confirm("Are you sure?");
 Prompt box
 Contains text, input field with default value:
prompt ("enter amount", 10);

20
JavaScript Prompt – Example
price = prompt("Enter the price", "10.00");
alert('Price + VAT = ' + price * 1.2);

21
The Core language Objects in JavaScript

22
Objects
In JavaScript, almost "everything" is an object.
 Booleans can be objects (or primitive data treated as objects)
 Numbers can be objects (or primitive data treated as objects)
 Strings can be objects (or primitive data treated as objects)
 Dates are always objects
 Maths are always objects
 Regular expressions are always objects
 Arrays are always objects
 Functions are always objects
 Objects are objects
 In JavaScript, all values, except primitive values, are objects.
23
Properties and Methods
 To access the properties of the object, we must specify the object name and the
property:
objectName.propertyName

 To access the methods of an object, we must specify the object name and the
required method:
objectName.method()

24
Using objects
 When creating a Web page we can insert:
 Browser objects
 Built in script language objects (vary depending on the scripting language
used)
 HTML elements
  We can also create our own objects for use in the programs.
 Object Hierarchy Browser Objects

Script Objects

HTML Elements 25
String object
 The string object is used to manipulate and work with strings of text.
 We can extract substrings and convert text to upper- or lowercase characters in a
program.
 The general syntax is,
stringName.propertyName

or
stringName.methodName()

26
String Operations
 The + operator joins strings
string1 = "fat ";
string2 = "cats";
alert(string1 + string2); // fat cats
 What is "9" + 9?
alert("9" + 9); // 99

 Converting string to number:


alert(parseInt("9") + 9); // 18

27
New Operator
 The new operator is used to create a new instance of an object type
 The object type may be user-define or built-in
objectName = new objectType (param1 [,param2] ...[,paramN])
where,
objectName is the name of the new object instance.
objectType is a function that defined the type of the object. For example,
Array.
param[1, 2, . . ] are the property values of the object

28
Create new Object
 With JavaScript, you can define and create your own objects.
 There are different ways to create new objects:
 Define and create a single object, using an object literal.
 Define and create a single object, with the keyword new.
 Define an object constructor, and then create objects of the constructed type.
 Step 1: Create new object by create a function
 Step 2: Create new instant by using new operator

29
Creating String object
 There are 3 different methods of creating strings.
 Using the var statement and optionally assigning it to a value.
 Using an assignment operator (=) with a variable name.
 Using the string () constructor.
<script type = "text/javascript">
var str = “Steve Paris!"
document.write("<p>" + str + "</p>")
document.write(str.length)
var pos=str.indexOf(“Paris")
if (pos>=0)
{ document.write(“Paris is found at position: ")
document.write(pos + "<br />") }
else
{ document.write(“Paris is not found!") }
</script>
30
Create new Object - Example
Example: Create an object named Customer:
 Properties: CustomeriD, CustomerName,CustomerAddress
 Method: DisplayInfor().
Step 1.
function Customer( iD,name,address)
{ this.CustomeriD = iD; //property
this.CustomerName = name; //property
this.CustomerAddress = address; //property
this.Displayinfor = information; //method
}

function DisplayInfor ()
{
document.write(“ID: ” + this.CustomeriD + ”<br>”);
document.write(“Name: ” + this.CustomerName + ”<br>”
document.write(“Address: ” + this.CustomerAddress + ”<br>”
}
31
Create new Object – Example (2)
Step 2.
var cust = new Customer();
cust.CustomeriD= “A01”
cust.CustomerName= “Steve Paris”
cust.CustomerAddress= “12 Orange Street”

 In order to display customer’s information, we call Displayinfor() method:


cust.Displayinfor()

32
Arrays Operations and Properties
 Declaring new empty array:
var arr = new Array();
 Declaring an array holding few elements:
var arr = [1, 2, 3, 4, 5];
 Appending an element / getting the last element:
arr.push(3);
var element = arr.pop();
 Reading the number of elements (array length):
arr.length;
 Finding element's index in the array:
arr.indexOf(1);

33
Math Object
 The Math object has properties and methods that represent advanced
mathematical calculations.

<script>
function doCalc(x) {
var a;
  a = Math.PI * x * x;
  alert ("The area of a circle with a radius of " + x + “
is " + a);
}
</script>

34
Math Object Example
for (i=1; i<=20; i++) {
var x = Math.random();
x = 10*x + 1;
x = Math.floor(x);
document.write("Random number (" + i + ") in range " + "1..10
--> " + x + "<br/>");
}

35
Date Object
 The Date object provides date / calendar functions

var now = new Date();


var result = "It is now " + now;
document.getElementById("timeField").innerText = result;
...
<p id="timeField"></p>

36
Timers: setTimeout()
 Make something happen (once) after a fixed delay
var timer = setTimeout('bang()', 5000);

5 seconds after this statement executes,


this function is called

clearTimeout(timer);

Cancels the timer

37
Timers: setInterval()
 Make something happen repeatedly at fixed intervals

var timer = setInterval('clock()', 1000);

This function is called


continuously per 1 second.

clearInterval(timer);

Stop the timer.

38
Date Object Example
<html><head> <body BGCOLOR="#FFFFFF” onLoad="startclock()">
<title>Digital Clock - Status Bar</title>
<script Language="JavaScript"> </body></html>
var timeriD = null;
var timerRunning = false;
function stopclock (){
if(timerRunning)
clearTimeout(timeriD);
timerRunning = false;
}
function showtime () {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds()
var timeValue = "" + ((hours >12) ? hours -12:hours)
timeValue += ((minutes < 10) ? ":0": ":") + minutes
timeValue += ((seconds < 10) ? ":0": ":") + seconds
timeValue += (hours >= 12) ? " P.M.": " A.M."
window.status = timeValue;
timeriD = setTimeout("showtime()",1000);
timerRunning = true; 39
}
Document Object Model (DOM)
and The Browser Objects in JavaScript

40
Event Object - Concept
 Events are a result of an action done by the user
 An event may be user-generated or generated by the system
 Each event has an associated event object. The event object provides
information on:
 the type of event
 the location of the cursor at the time of the event
 The event object is used as a part of an event handler

41
Event – Life Cycle
 Events are a result of an action done by the user
 An event may be user-generated or generated by the system
 Each event has an associated event object. The event object provides
information on:
 the type of event
 the location of the cursor at the time of the event
 The event object is used as a part of an event handler

42
JavaScript Event
 Common events supported by JavaScript includes:
 onClick
 onChange
 onFocus
 onBlur
 onMouseOver
 onMouseOut
 onLoad
 onSubmit
 onMouseDown
 onMouseUp

43
onClick - Example
 The onClick event is generated whenever the user clicks the mouse button on
certain form elements or on a hypertext link.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function compute(form)
{
if (confirm("Are you sure?"))
form.result.value = eval(form.expr.value)
else
alert("Please come back again.")
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
44
onClick – Example (2)

Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15 ><BR><BR>
<INPUT TYPE="button" VALUE="Calculate" ONCLICK="compute(this.form)">
<BR><BR><BR> Result: <INPUT TYPE="text" NAME="result" SIZE=15 >
<BR>
</FORM>
</BODY>
</HTML>

45
onChange - Example
 The onChange event occurs whenever a form element changes. This can happen
whenever the contents of a text control changes, or when a selection in a
selection list changes.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--- hide script from old browsers
function checkNum(num)
{
if (num == "")
{
alert("Please enter a number");
return false;
}
if (isNaN (num))
{
alert("Please enter a numeric value");
return false; 46
onChange - Example
else
alert ("Thank you");
}
// end hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY bgColor = white>
<FORM> Please enter a number:
<INPUT type = text size = 5 onChange="checkNum(this.value)">
</FORM>
</BODY>
</HTML>

47
onFocus/onBlur/onMouseOver/
onMouseOut
 onFocus
 The onFocus event is sent whenever a form element becomes the current form
element. Only when an element has the focus can it accept input from the user.
 onBlur
 Blur is the opposite of focus. When the user leaves a form element, the onBlur
event is activated.
 onMouseOver
 The onMouseOver event is generated whenever the mouse cursor is moved
over an element.
 onMouseOut
 The onMouseOut event is generated whenever the mouse cursor moves off of
an element.

48
onLoad/onSubmit/onMouseDown/
onMouseUp
 OnLoad
 The onLoad event is sent to the document body object when the document
has finished loading.
 onSubmit
 The onSubmit event is generated whenever the user submits a form (using the
"Submit" button). The event occurs before the form is actually submitted.
 onMouseDown
 The event is activated when a MouseDown event occurs. That is, when the
user depresses a mouse button.
 onMouseUp
 The event is activated when a MouseUp event occurs. That is, when the user
releases a mouse button.

49
Document Object Model (DOM)
 Every HTML element is accessible via the JavaScript DOM API
 Most DOM objects can be manipulated by the programmer
 The event model lets a document to react when the user does something on the
page
 Advantages
 Create interactive pages
 Updates the objects of a page without reloading it

50
Browser Objects
 A browser is an application that is used to display the contents of an HTML
document
 Browsers also expose some objects that can be accessed and used in script

IE Browser Objects Netscape Browser Objects 51


Accessing Elements
 Access elements via their ID attribute
var elem = document.getElementById("some_id")
 Via the name attribute
var arr = document.getElementsByName("some_name")
 Via tag name
var imgTags = el.getElementsByTagName("img")
 Returns array of descendant <img> elements of the element "el"

52
DOM Manipulation
 Once we access an element, we can read and write its attributes

function change(state) {
var lampImg = document.getElementById("lamp");
lampImg.src = "lamp_" + state + ".png";
var statusDiv = document.getElementById("statusDiv");
statusDiv.innerHTML = "The lamp is " + state";
}

<img src="test_on.gif" onmouseover="change('off')"
onmouseout="change('on')" />

53
Common Element Properties
 Most of the properties are derived from the HTML attributes of the tag
 E.g. id, name, href, alt, title, src, etc…
 style property – allows modifying the CSS styles of the element
 Corresponds to the inline style of the element
 Not the properties derived from embedded or external CSS rules
 Example:
 style.width,
 style.marginTop,
 style.backgroundImage

54
Common Element Properties (2)
 className – the class attribute of the tag
 innerHTML – holds all the entire HTML code inside the element
 Read-only properties with information for the current element and its state
 tagName, offsetWidth, offsetHeight, scrollHeight, scrollTop,
nodeType, etc…

55
Accessing Elements through the DOM
Tree Structure
 We can access elements in the DOM through some tree manipulation properties:
 element.childNodes
 element.parentNode
 element.nextSibling
 element.previousSibling
 element.firstChild
 element.lastChild

56
Accessing Elements through the
DOM Tree – Example
var el = document.getElementById('div_tag');
alert (el.childNodes[0].value);
alert (el.childNodes[1].getElementsByTagName('span').id);

<div id="div_tag">
<input type="text" value="test text" />
<div>
<span id="test">test span</span>
</div>
</div>
 Warning: may not return what you expected due to Browser differences

57
The Built-In Browser Objects

58
The Built-In Browser Objects (2)
 The browser provides some read-only data via:
 window
 The top node of the DOM tree
 Represents the browser's window
 document
 holds information the current loaded document
 screen
 Holds the user’s display properties
 browser
 Holds information about the browser
59
Opening New Window – Example
var newWindow = window.open("", "sampleWindow",
"width=300, height=100, menubar=yes,
status=yes, resizable=yes");

newWindow.document.write("<html><head><title>Sample
Title</title></head><body><h1>Sample Text</h1></body>");

newWindow.status = "Hello folks";

60
The Navigator Object
alert(window.navigator.userAgent);

The browser The navigator in the The userAgent


window browser window (browser ID)

61
The Screen Object
 The screen object contains information about the display

window.moveTo(0, 0);
x = screen.availWidth;
y = screen.availHeight;
window.resizeTo(x, y);

62
Document and Location
 document object
 Provides some built-in arrays of specific objects on the currently loaded Web
page
document.links[0].href = "yahoo.com";
document.write("This is some <b>bold text</b>");

 document.location
 Used to access the currently open URL or redirect the browser

document.location = "http://www.yahoo.com/";

63
Form Object
 Form object consist of three attributes:
 Accept
 Action
 Method
 For Example:
<form action="Simple.htm“ accept=“TEXT/HTML”
method=“POST”>

64
Form Validation
 Validate each and every important field by ensuring that none of the fields are
empty.
 Also the fields should not contain any invalid information.
 Consider an example:

65
Form Validation – Example
function checkForm()
{
var valid = true;
if (document.mainForm.firstName.value == "") {
alert("Please type in your first name!");
document.getElementById("firstNameError").
style.display = "inline";
valid = false;
}
return valid;
}

<form name="mainForm" onsubmit="return checkForm()">
<input type="text" name="firstName" />

</form>
66
67

You might also like