You are on page 1of 49

1 Client-side Scripting Language

Chapter 4
What is Java script?
2

 a lightweight programming language ("scripting


language")
 used to make web pages interactive
 insert dynamic text into HTML

 react to events (ex: user click)

 get information about a user's computer (ex: browser


type)
 perform calculations on user's computer

 Generally-Defines behavior of web pages


What is Javascript?
3

 a web standard (but not supported identically by all


browsers)
 NOT related to Java other than by name and some
syntactic similarities
Javascript vs Java
4

 interpreted, not compiled


 more relaxed syntax and rules
 fewer and "looser" data types
 variables don't need to be declared

 errors often silent (few exceptions)

 key construct is the function rather than the class


 "first-class" functions are used in many situations
 contained within a web page and integrates with its
HTML/CSS content
Variables
5

var name = expression; JS

var clientName = "Connie Client";


var age = 32;
var weight = 127.4; JS
 variables are declared with the var keyword (case
sensitive)
 Equal sign is used to assign values to variables.
 types are not specified, but JS does have types
("loosely typed")
 Re-declaring variable will not change it’s previous
value
Number type
6

var enrollment = 99;


var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3);
JS

 integers and real numbers are the same type (no int
vs. double)
 same operators: + - * / % ++ -- = += -= *= /= %=
 similar precedence to Java
 many operators auto-convert types: "2" * 3 is 6
Comments (same as Java)
7

// single-line comment
/* multi-line comment */
JS

 identical to Java's comment syntax


 recall: 4 comment syntaxes
 HTML: <!-- comment -->
 CSS/JS/PHP: /* comment */

 Java/JS/PHP: // comment

 PHP: # comment
Special values: null and undefined
8

var ned = null;


var benson = 9;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined JS
 undefined : has not been declared,does not exist
 null : exists, but was specifically assigned an
empty or null value
 Both are equal in value, but different in type
 Null – is object and undefined- is undefined in type
Logical operators
9

 > < >= <= && || ! == != === !==


 most logical operators automatically convert types:
5 < "7" is true
 42 == 42.0 is true

 "5.0" == 5 is true

 === and !== are strict equality tests; checks both


type and value
 "5.0" === 5 is false
if/else statement (same as Java)
10

if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
JS
 identical structure to Java's if/else statement
 JavaScript allows almost anything as a condition
Boolean type
11

var iLike190M = true;


var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /* true */ }
if (0) { /* false */ }
JS
 any value can be used as a Boolean
 "falsey" values: 0, 0.0, NaN, "", null, and undefined
 "truthy" values: anything else

 converting a value into a Boolean explicitly:


 var boolValue = Boolean(otherValue);
 var boolValue = !!(otherValue);
JavaScript functions
12

function name() {
statement ;
statement ;
...
statement ;
} JS
function myFunction() {
alert("How are you?");
} JS

 JavaScript functions are defined with the function


keyword followed by a name & parenthesis
 JavaScript function is invoked when something
invokes it (calls it)—event-driven.
Functions generating event
13

 onsubmit - called when submit button is clicked


 onclick - called when this button is clicked
 onreset - called when the reset button is clicked
 onload - called after page loads
 onmouseover - called when mouse pointer enters image area
 onmouseout - called when mouse pointer leaves image area
 onfocus - called when control receives focus
 onblur - called when a control loses focus
 onchange - called when a control loses focus and the value of its
contents has changed
 And many more ….
Calling a function
14

<html> <head><title>Function calling </title>


<script type=“text/javascript”>
function sayHello(){
alert(“hello there”);
}
</script>
</head>
<body>
<h3>Click the following button to call the function</h3>
<form method=“Post” action=“ “>
<input type=“button” onclick=“sayHello()” value=“Click”>
</form>
</body>
</html>
JS
Linking to a JavaScript file
15

<script src="filename.js" type="text/javascript"></script>


HTML

 script tag should be placed in HTML page's head


 script code is stored in a separate .js file
 JS code can be placed directly in the HTML file's
body or head (like CSS)
 but this is bad style (should separate content,
presentation, and behavior
for loop (same as Java)
16

var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
} JS

var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo" JS
while loops (same as Java)
17

while (condition) {
statements;
} JS

do {
statements;
} while (condition);
JS

 break and continue keywords also behave as in


Java
Popup boxes
18

alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS
HTML DOM
19

 When a web page is loaded, the browser creates a


Document Object Model of the page.
 It is constructed as a tree of objects:
Document

Root element
<HTML>

Element
Element <head> <body>

Element :<a
>
Element <title>
Attribute:”href”

Text:”My link”
Text: “My title”
HTML DOM
20

 Is a w3c standard for accessing web documents


 It is a standard for how to :
 Get

 Change

 Add or
 Delete HTML elements

 Treats all HTML elements as objects


HTML DOM Methods
21

 HTML DOM methods are actions you can perform


on HTML Elements
 The following are some of the methods:
 document.getElementById(id)

 document.getElementsByTagName(name)

 document.getElementsByClassName(name)
Example
22

<html>
<head>
<title>Change attribute value</title>
</head>
<body>
<img id="myImage" src="xxx.jpg" width="200" height="200">
<script>
function change(){
document.getElementById("myImage").src="bb.jpg";
}
</script>
<form method="get">
<input type="button" onclick="change()" value="click">
</form>
</body>
</html> JS
HTML DOM Property
23

 Property is a value that you can get or set (like


changing the content of an HTML element)
 element.innerHTML=new value
 element.attribute=new value

 element.setAttribute(attribute,value)

 element.style.property=new style
Example
24

<html> <head>
<script type="text/javascript">
function sayHello(){
document.getElementById("a1").innerHTML="Heading four";
}
</script>
</head>
<body>
<h3>Click the following button to call the function</h3>
<form method="Post">
<input type="button" onclick="sayHello()" value="Click">
</form>
<h4 id="a1">use different text in write and try</h4>
</body>
</html> JS
HTML DOM ….
25

 Methods used for Adding or deleting elements:


 document.createElement(element)

 document.removeChild(element)

 document.replaceChild(element)

 document.write(text)
Example
26
HTML4 FORM SHOULD BE
VALIDATED WITH
JAVA SCRIPT

NOT HTML5 FORM ELEMENT

27
A real Form that uses validation
28
What is form validation?
29

 validation: ensuring that form's values are correct


 some types of validation:
 preventing blank values (email address)
 ensuring the type of values
 integer, real number, currency, phone number, Social Security
number, postal
 address, email address, date, credit card number,
 ensuring the format and range of values (ZIP code must be
a 5-digit integer)
 ensuring that values fit together (user types email twice,
and the two must match)
Example
30

<html><head>
<title>Validation</title>
<script>
function validate(){
var n=document.getElementById("name").value;
var a=document.getElementById("age").value;
if(n=="" || !isNaN(n))
alert("Enter valid name");
else if(a=="" || isNaN(a))
alert("Enter valid age"); }
</script>
</head><body>
<form method="post" action="“ >
Name:<br><input type="text" id="name"><br>
Age:<br><input type="text" id="age"><br>
<input type="button" value="Submit" onclick="validate()">
</form></body></html> JS
Advantages
31

1. Less server interaction − You can validate user


input before sending the page off to the server.
2. Immediate feedback to the visitors − They don't
have to wait for a page reload to see if they have
forgotten to enter something.
…cont’d…
32

1. Increased interactivity − You can create


interfaces that react when the user hovers over
them with a mouse or activates them via the
keyboard.
2. Richer interfaces − You can use JavaScript to
include such items as drag-and-drop components
and sliders to give a Rich Interface to your site
visitors.
JavaScript Regular Expressions
33

 A regular expression is a particular representation


of a set of strings
 E.g: JavaScript regular expression representing the set
of syntactically-valid US telephone area codes (three-
digit numbers):

 \d represents the set {“0”, “1”, …, “9”}


JavaScript Regular Expressions
34

 Using regular expressions in JavaScript


JavaScript Regular Expressions
35

 Using regular expressions in JavaScript

Variable containing string to be tested


JavaScript Regular Expressions
36

 Using regular expressions in JavaScript


Regular expression as String (must escape \)
JavaScript Regular Expressions
37

 Using regular expressions in JavaScript


Built-in constructor
JavaScript Regular Expressions
38

 Using regular expressions in JavaScript

Method inherited by RegExp instances:


returns true if the argument contains a
substring in the set of strings represented by
the regular expression
JavaScript Regular Expressions
39

 Using regular expressions in JavaScript


Represents beginning of string Represents end of string

This expression matches only strings with


exactly three digits (no other characters,
even white space)
JavaScript Regular Expressions
40

 Using regular expressions in JavaScript

Represents all strings that begin


with three digits

 Alternate syntax:

Regular expression literal.


Do not escape \.
JavaScript Regular Expressions
41

 Simplest regular expression is any character that is


not a special character:

 E.g: _ is a regular expression representing {“_”}


 Backslash-escaped special character is also a
regular expression
 E.g: \$ represents {“$”}
JavaScript Regular Expressions
42

 Special character . (dot) represents any character


except a line terminator
 Several escape codes are regular expressions
representing sets of chars:
JavaScript Regular Expressions
43

 Three types of operations can be used to combine


simple regular expressions into more complex
expressions:
 Concatenation
 Union (|)

 Kleene star (*)


JavaScript Regular Expressions
44

 Concatenation
 Example:
String consisting entirely of four characters:
 Digit followed by
 A . followed by
 A single space followed by
 Any “word” character

 Quantifier shorthand syntax for concatenation:


JavaScript Regular Expressions
45

 Union
E.g:
Union of set of strings represented by regular
expressions
 Set of single-character strings that are either a digit or a
space character
 Character class: shorthand for union of one or more
ranges of characters
 E.g: set of lower case letters
 E.g: the \w escape code class
JavaScript Regular Expressions
46

 Unions of concatenations

 Note that concatenation has higher precedence than


union
 Optional regular expression
JavaScript Regular Expressions
47

 Kleene star
 E.g: any number of digits (including none)
 E.g:
 Strings consisting of only “word” characters
 String must contain both a digit and a letter (in either order)
Example code
48
THANKS!
YOU CAN DIG MORE …

49

You might also like