Javascript: Web Engineering
Javascript: Web Engineering
Javascript: Web Engineering
Web Engineering
1
Client-Side Programming
HTML is good for developing static pages
can specify text/image layout, presentation, links, …
in order to develop interactive/reactive pages, must integrate programming in some form or
another
• client-side programming
programs are written in a separate programming (or scripting) language
e.g., JavaScript, JScript, VBScript
programs are embedded in the HTML of a Web page, with (HTML) tags to identify the
program component
e.g., <script type="text/javascript"> … </script>
the browser executes the program as it loads the page, integrating the dynamic output of
the program with the static content of HTML
could also allow the user (client) to input information and process it, might be used to
validate input before it’s submitted to a remote server
Scripts vs. Programs
a scripting language is a simple, interpreted programming language
scripts are embedded as plain text, interpreted by application
JavaScript 1.5 & JScript 5.0 cores both conform to ECMAScript standard
programming language)
JavaScript code is usually embedded directly into HTML pages
5
What is JavaScript?
JavaScript gives HTML designers a programming tool
JavaScript can put dynamic text into an HTML page
JavaScript can react to events
JavaScript can read and write HTML elements
JavaScript can be used to validate input data
JavaScript can be used to detect the visitor‘s browser
JavaScript can be used to create cookies
6
JavaScript
JavaScript code can be embedded in a Web page using <script>
tags
document.write displays text in the page
the output of JavaScript code is displayed as if directly entered in
<html>
text to be displayed can include HTML
HTML
<head>
tags
<title>JavaScript Page</title>
</head>
the tags are interpreted by the browser
<body> as normal when the text is displayed
<script type="text/javascript">
8
Where to Place Scripts?
Where to Put the JavaScript
Scripts in the body section will be executed WHILE the page loads.
Scripts in the head section will be executed when CALLED.
9
Example
Put a JavaScript Into an HTML Page
<html> <body> <script type="text/javascript"> document.write("Hello
World!") </script> </body> </html>
The code above will produce this output on an HTML page:
Hello World!
Explanation:
Use the <script> tag. Use the type attribute
<script type="text/javascript">:
10
Defining Variables
11
JavaScript let
12
Defining Functions
13
Defining Functions
14
Defining Functions
15
Defining Functions
16
Defining Functions
17
Scope
18
Scope Chain
19
Scope Chain
20
Defining Variables, Function, and Scope
21
Example
22
Example
23
JavaScript Operators & Control Statements
standard C++/Java operators & control
<html> statements are provided in JavaScript
<head> • +, -, *, /, %, ++, --, …
<title>Folding Puzzle</title> • ==, !=, <, >, <=, >=
</head> • &&, ||, !,===,!==
<body> • if , if-else, switch
<script type="text/javascript">
var distanceToSun = 93.3e6*5280*12; • while, for, do-while, …
var thickness = .002;
<body> Math.sqrt
<div style="text-align:center"> Math.pow
<script type="text/javascript"> Math.abs
var roll1 = Math.floor(Math.random()*6) + 1;
var roll2 = Math.floor(Math.random()*6) + 1;
Math.max
Math.min
document.write("<img src='http://www.csc.liv.ac.uk/"+ Math.floor
"~martin/teaching/comp519/Images/die" + Math.ceil
roll1 + ".gif' alt='die showing " + roll1 + "'/>"); Math.round
document.write(" ");
document.write("<img src='http://www.csc.liv.ac.uk/"+
Math.PI
"~martin/teaching/comp519/Images/die" +
roll2 + ".gif' alt='die showing " + roll2 + "'/>"); Math.E
</script>
</div> Math.random
</body> function returns a real
</html>
number in [0..1)
view page
JavaScript Popup Boxes
Alert box
User will have to click "OK" to proceed
alert("sometext")
Confirm box
User will have to click either "OK" or "Cancel" to proceed
confirm("sometext")
Prompt box
User will have to click either "OK" or "Cancel" to proceed
after entering an input value
prompt("sometext","defaultvalue")
26
alert(), confirm(), and prompt()
<script type="text/javascript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>
alert() and confirm()
alert("Text to be displayed");
Display a message in a dialog box.
The dialog box will block the browser.
If the user click the "OK" button, prompt() returns the value
in the input textfield as a string.
If the user click the "Cancel" button, prompt() returns null.
JavaScript Language
Conditional statement
> if, if.. else, switch
Loop
> for loop, while loop
try...catch
throw
•Function can be called from anywhere within the page (or even
from other pages if the function is embedded in an external .js
file).
31
User-Defined Functions
function definitions are similar to C++/Java, except:
no return type is specified for the function (since variables are loosely typed)
no variable typing for parameters (since variables are loosely typed)
by-value parameter passing only (parameter gets copy of argument)
function isPrime(n)
// Assumes: n > 0 and is an integer Can limit variable scope to the function.
// Returns: true if n is prime, else false
{ if the first use of a variable is preceded
if (n < 2) {
return false; with var, then that variable is local to
} the function
else if (n == 2) {
return true;
}
for modularity, should make all
else { variables in a function local
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
33
Function Example
<html>
36
you are used to programs that start with a main method
(or implicit main like in PHP)
JavaScript programs instead wait for user actions
called events and respond to them
event-driven programming: writing programs driven
by user events
Let's write a page with a clickable button that pops up
a "Hello, World" window...
37
38
Event handlers
39
Events & Event Handlers
• Every element on a web page has certain events which can
trigger invocation of event handlers
• Attributes are inserted into HTML tags to define events
and event handlers
• Examples of events
• A mouse click
• A web page or an image loading
• Mouse hovering over a hot spot on the web page
• Selecting an input box in an HTML form
• Submitting an HTML form
• A keystroke
40
Events
41
Events
onload - A page or an image is finished loading
onmousedown - A mouse button is pressed
onmousemove - The mouse is moved
onmouseout - The mouse is moved off an element
onmouseover - The mouse is moved over an element
onmouseup - A mouse button is released
onreset - The reset button is clicked
onresize - A window or frame is resized
onselect - Text is selected
onsubmit - The submit button is clicked
onunload - The user exits the page
42
onload & onUnload Events
• The onload and onUnload events are triggered when the
user enters or leaves the page
• Both the onload and onUnload events are also often used
to deal with cookies that should be set when a user enters
or leaves a page
43
onFocus, onBlur and onChange
• The onFocus, onBlur and onChange events are often used in
combination with validation of form fields.
44
45
onSubmit
• The onSubmit event is used to validate all form fields before
submitting it.
<a href="http://www.w3schools.com”
onmouseover="alert('An onMouseOver event) </a>
48
JavaScript Object
JavaScript is an Object Oriented Programming (OOP)
language.It supports programming with objects.
• Methods are the actions that the object can perform or that
can be performed on the object.
Examples: alert, confirm, write, open, close
50
Naming Objects
• Objects are organized in a hierarchy.
• To refer to an object use :
objectName
• To refer to a property of an object use:
objectName.propertyName
• To refer to a method of an object use:
objectName.methodName()
to create a String in JavaScript, assign using new keyword or (in the case of a String) just
make a direct assignment (new is implicit for a String assignment)
word = new String("foo"); word = "foo";
<script type="text/javascript">
function strip(str){
// CODE AS SHOWN ON PREVIOUS SLIDE
}
function isPalindrome(str){
// CODE AS SHOWN ON PREVIOUS SLIDE
}
</script>
</head>
<body> <p>
<script type="text/javascript">
text = prompt("Enter a word or phrase", "Madam, I'm Adam");
if (isPalindrome(text)) {
document.write("'" + text + "' <b>is</b> a palindrome.");
}
else {
document.write("'" + text + "' <b>is not</b> a palindrome.");
}
</script> </p>
</body>
</html>
JavaScript Arrays
Arrays store a sequence of items, accessible via an index
Since JavaScript is loosely typed, elements do not have to be the same type
To create an array, allocate space using new (or can assign an array directly using the
proper syntax shown below)
items = new Array(10); //allocates space for 10 items (but can grow)
Methods include:
newYear.getYear() can access individual components of a date
newYear.getMonth()
newYear.getDay()
newYear.getHours()
newYear.getMinutes()
newYear.getSeconds()
newYear.getMilliseconds()
Date Example
<html>
<head>
<title>Time page</title> by default, a date will be displayed in
</head> full, e.g.,
<body>
Time when page was loaded: Sun Feb 03 22:55:20 GMT-0600
<script type="text/javascript"> (Central Standard Time) 2002
now = new Date();
document.write("<p>" + now + "</p>");
time = "AM"; can pull out portions of the date using
hours = now.getHours();
if (hours > 12) { the methods and display as desired
hours -= 12;
time = "PM" here, determine if "AM" or "PM" and
} adjust so hour between 1-12
else if (hours == 0) {
hours = 12; 10:55:20 PM
}
document.write("<p>" + hours + ":" +
now.getMinutes()
+ ":" + now.getSeconds() + " " +
time + "</p>");
</script>
</body>
</html>
Another Date Example
<html>
<head>
<title>Time page</title> you can add and subtract Dates:
</head>
<body>
the result is a number of
<p>Elapsed time in this year: milliseconds
<script type="text/javascript">
now = new Date(); here, determine the number of
newYear = new Date(2014,0,1); seconds since New Year's day
secs = Math.round((now-newYear)/1000);
days = Math.floor(secs / 86400);
(note: January is month 0)
secs -= days*86400;
hours = Math.floor(secs / 3600); divide into number of days, hours,
secs -= hours*3600; minutes and seconds
minutes = Math.floor(secs / 60);
secs -= minutes*60
document.write(days + “days,”+hours+ “hours,”+
minutes +”minutes, and”+
secs + " seconds.");
</script>
</p>
</body>
</html>
Create Custom Objects
• With JavaScript you can define and create your own
objects. There are 2 different ways to create a new object:
• Define and create a direct instance of an object.
• Use a function to define an object, then create new object
instances.
60
Option 1: Creating a Direct Instance
of a JavaScript Object
• By invoking the built-in constructor for the Object class
personObj=new Object(); // Initially empty with no properties or
methods
• Add properties to it
personObj.firstname="John“;
personObj.age=50;
62
Option 2: Creating a template of a
JavaScript Object
• The template defines the structure of a JavaScript object in
the form of a function.
64
person.js job.js main.js
function Person(name, age, gender) function Job(title) { function main() {
{ this.title = title; var employee = new
this.age = age; this.description; Person("Richard", 23, male);
this.name = name; this.setDescription = document.getElementById("
this.gender = gender; function(description) mainBody").innerHTML =
this.job; { this.description = employee.getName(); }
this.setJob = function(job) {
description; } }
this.job = job; }
this.getAge = function() {
return this.age; }
this.getName = function() { <!DOCTYPE HTML>
return this.name; } <HTML>
<head> <title>javascript test</title>
this.getGender = function() {
<script src="person.js" type=“text/javascript"></script>
return this.gender; } } <script src="Job.js" type=“text/javascript"></script>
<script src="main.js" type=“tex/javascript"></script>
</head>
<body>
<p id="mainBody"></p>
65 </body>
</HTML>
The Browser Object Hierarchy
66
The Browser Objects (Global DOM)
67
The window object
the entire browser window (DOM top-level
object)
technically, all global code and variables
become part of the window object properties:
document, history, location, name
methods:
alert, confirm, prompt (popup boxes)
setInterval, setTimeoutclearInterval, clearTimeout (timers)
open, close (popping up new browser windows)
blur, focus, moveBy, moveTo, print, resizeBy, resizeTo,
scrollBy, scrollTo
68
Window object
<script>
<!DOCTYPE html>
var myWindow;
<html>
function openWin() {
<body>
myWindow = window.open("", "myWindow", "width=400,
<button onclick="openWin()">Open "myWindow"</button>
height=200");
}
<button onclick="closeWin()">Close "myWindow"</button>
function closeWin() {
<br><br>
if (myWindow) {
myWindow.close();
<button onclick="checkWin()">Has "myWindow" been
closed?</button> }}
<body> window.history.back();
}
</script>
<button onclick="goBack()">Go
Back</button>
</body>
</html>
70
Document Object Model
71
HTML DOM Objects
• The HTML DOM defines a standard set of objects for HTML,
and a standard way to access and manipulate HTML
documents.
<html>
<head>
<title>Sample DOM Document</title>
</head>
<body>
<h1>An HTML Document</h1>
<p>This is a <i>simple</i> document.
</body>
</html>
<head> <body>
<title>
"simple"
The HTML DOM Tree
75
Types of DOM nodes
<p>
This is a paragraph of text with a
<a href="/path/page.html">link in it</a>.
</p> HTML
77 CS380
HTML DOM
HTML DOM methods are actions you can perform (on HTML Elements)
add or deleting an HTML element
HTML DOM properties are values (of HTML Elements) that you can set or change
changing the content of an HTML element
html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html
Document Object: Write text to the
output
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
79
Document Object: Write text with Formatting to
the output
<html>
<body>
<script type="text/javascript">
document.write("<h1>Hello World!</h1>")
</script>
</body>
</html>
80
Some information from a document
<html>
<head>
<title>DOM Sample 1</title>
</head>
<body>
Information about this document.<br>
<script type="text/javascript">
document.write("<br>Title: ",document.title);
document.write("<br>Referrer: ",document.referrer);
document.write("<br>Domain: ",document.domain);
document.write("<br>URL: ",document.URL);
</script>
</body>
</html>
Finding HTML Elements
82
Document Object: Use
getElementById()
<html>
<head>
<script type="text/javascript">
function getElement() {
var x=document.getElementById("myHeader")
alert("I am a " + x.tagName + " element“) }
</script> </head>
<body>
<h1 id="myHeader" onclick="getElement()">Click to see what
element I am!</h1>
</body>
</html>
83
JavaScript function to get the values of First
and Last name of form.
<!DOCTYPE html> function getFormvalue() {
<html>
var firstname =
<head>
(document.getElementsByName("
<title> fname"))[0].value;
Return first and last name from a form var secondname =
</title> (document.getElementsByName("
</head> lname"))[0].value;
<body> alert(firstname+ " " +
<form id="form1" onsubmit="getFormvalue()"> secondname);
First name: <input type="text" name="fname" }
value=“Ahmad"><br>
Last name: <input type="text" name="lname"
value=“Ali"><br>
<input type="submit" value="Submit">
</form> </body> </html>
84
Example
<html>
<body>
<script>
var myElement = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"The text from the intro paragraph is " + myElement.innerHTML;
</script> Hello World!
</body> This example demonstrates the
</html> getElementById method!
The text from the intro paragraph is Hello
85 World!
JavaScript function to add rows to a table
<html> function insert_Row() {
<head> var x=
<title>Insert row in a table </title>
document.getElementById('sampleTable').insert
</head> Row(0);
<body>
<table id="sampleTable" border="1">
var y = x.insertCell(0);
<tr>
<td>Row1 cell1</td> var z = x.insertCell(1);
<td>Row1 cell2</td> y.innerHTML="New Cell1";
</tr> z.innerHTML="New Cell2"; }
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
</table><br>
<input type="button" onclick="insert_Row()"
86value="Insert row">
</body></html>
<html>
JavaScript: Remove items from a dropdown list
function removecolor()
<head> {
<style type="text/css">
var x=
body {margin: 30px;}
</style>
document.getElementById("colorSelect
<title>Remove items from a dropdown list
");
</title>
</head>
x.remove(x.selectedIndex);
<body> }
<form>
<select id="colorSelect">
<option>Red</option>
<option>Green</option>
<option>White</option>
<option>Black</option>
</select>
<input type="button" onclick="removecolor()"
value="Select and Remove">
</form>
87
</body>
getElementsByTagName()
getElementById() allows you to work with elements
by their individual id but often you will want to work
with a group of elements
getElementsByTagName() allows you to work with
groups of elements. This method returns an array
88
Example
<html>
<body>
<p>Hello World!</p>
<p id="demo"></p>
<p id="demo"></p>
<script>
var x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
</script>
</body>
91
</html>
Finding HTML Objects
Property Description
document.anchors Returns all <a> elements that have a
name attribute
document.forms Returns all <form> elements
document.images Returns all <img> elements
document.title Returns the <title> element
document.URL Returns the complete URL of the
document
92
Document Object: Return the innerHTML of the
first anchor in a document
<html>
<body>
<a name="first">First anchor</a><br />
<a name="second">Second anchor</a><br />
<a name="third">Third anchor</a><br />
<br />
InnerHTML of the first anchor in this document:
<script type="text/javascript">
document.write(document.anchors[0].innerHTML)
</script>
</body>
93
</html>
Document Object: Access an item in a
collection
<html>
<body>
<form id="Form1" name="Form1">
Your name: <input type="text">
</form>
<form id="Form2" name="Form2">
Your car: <input type="text">
</form>
<p> To access an item in a collection you can either use the number or the name of the
item:</p>
<script type="text/javascript">
document.write("<p>The first form's name is: " + document.forms[0].name + </p>")
document.write("<p>The first form's name is: " +
document.getElementById("Form1").name + "</p>")
</script> </body>
94
</html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return
validateForm()" method="post">
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Number of anchors are: " + document.anchors.length;
</script>
96 </body>
</html>
Changing HTML Elements
97
JavaScript HTML DOM - Changing CSS
The HTML DOM allows JavaScript to change the style of HTML elements.
Changing HTML Style
document.getElementById(id).style.property=new style
<html>
<body>
<script>
document.getElementById("p2").style.color="blue";
</script>
</body>
</html>
98
Modify paragraph text style through javascript code using
button
<!DOCTYPE html>
function js_style() {
<html> //font styles added by JS:
<head> text.style.fontSize = "14pt";
<title>JS DOM paragraph style</title> text.style.fontFamily = "Comic Sans
</head> MS";
<body> text.style.color = "green"; }
<p id ='text'>JavaScript Exercises -
modify text style</p>
<div>
<button id="jsstyle”
onclick="js_style()">Style</button>
</div>
</body>
</html>
99
JavaScript HTML DOM Events
<html>
<head>
<script>
function changetext(id){
id.innerHTML="Ooops!";
}
</script>
</head>
<body>
<h1 onclick="changetext(this)">Click on this text!</h1>
</body>
</html>
100
Creating new nodes
101
Modifying the DOM tree
102
Unobtrusive JavaScript
103
Unobtrusive JavaScript
104
Obtrusive event handlers (bad)
105
Attaching an event handler in JavaScript
code
106
When does my code run?
107
When does my code run?
108
A failed attempt to be unobtrusive
109
The window.onload event
110
An unobtrusive event handler
111
Anonymous functions
112
Anonymous function example
113
The keyword this
114
The keyword this
115
116