Download - Webpage Lecture Four
-
7/31/2019 Webpage Lecture Four
1/87
1
Introduction to JavaScript
Creating a Programmable Web Page
ITEC 464
INFORMATION TECHNOLOGYChapter Four
Internet and Webpage Design
-
7/31/2019 Webpage Lecture Four
2/87
22
Objectives
Understand basic JavaScript syntax Create an embedded and external script Work with variables and data Work with expressions and operators Create and call a JavaScript function
Work with arrays and conditional statements Learn about program loops Work with data objects and extract values
from dates
-
7/31/2019 Webpage Lecture Four
3/87
3
JavaScript
JavaScript is used in millions of web pages toimprove the design, validate forms, and much
more. JavaScript was developed by Netscape
The most popular scripting language on theInternet.
JavaScript works in all major browsers that areversion 3.0 or higher.
-
7/31/2019 Webpage Lecture Four
4/87
44
Client-Side Programs
solve many of the problems associated with server-side scripts
can be tested locally without first uploading it to a Web
server
are likely to be more responsive to the user
can never completely replace server-side scripts
Server-Side Programs
A user must be connected to the Web server to runthe server-side script
-
7/31/2019 Webpage Lecture Four
5/87
55
Introduction to JavaScript
JavaScript is an interpreted programming or scriptlanguage from Netscape.
JavaScript is used in Web site development to such thingsas:
automatically change a formatted date on a Web page
cause a linked-to-page to appear in a popup window
cause text or a graphic image to change during a mouserollover
-
7/31/2019 Webpage Lecture Four
6/87
66
Java vs. JavaScript
Requires the JDK to create theapplet
Requires a Java virtual machineto run the applet
Applet files are distinct from theXHTML and HTML code
Source code is hidden from theuser
Programs must be saved asseparate files and compiledbefore they can be run
Programs run on the server side
Requires a text editor
Required a browser that can
interpret JavaScript code JavaScript can be placed within
HTML and XHTML
Source code is made accessibleto the user
Programs cannot write content tothe hard disk
Programs run on the client side
-
7/31/2019 Webpage Lecture Four
7/8777
ECMAScript
The responsibility for the development of a scriptingstandard has been transferred to an international body
called the European Computer ManufacturersAssociation (ECMA).
The standard developed by the ECMA is calledECMAScript, though browsers still refer to it as
JavaScript. The latest version is ECMA-262, which is supported by
the major browsers.
-
7/31/2019 Webpage Lecture Four
8/8788
Other Client-side Languages
Internet Explorer supports JScript.
JScript is identical to JavaScript, but there are someJavaScript commands not supported in JScript, andvice versa.
Other client-side programming languages are also
available to Web page designers, such as the InternetExplorer scripting language, VBScript.
-
7/31/2019 Webpage Lecture Four
9/879
9
Example of Web Site usingJavaScript
-
7/31/2019 Webpage Lecture Four
10/8710 10
Writing a JavaScript Program
The Web browser runs a JavaScript program when theWeb page is first loaded, or in response to an event.
JavaScript programs can either be placed directly into theHTML file or they can be saved in external files.
placing a program in an external file allows you to hidethe program code from the user
source code placed directly in the HTML file can beviewed by anyone
-
7/31/2019 Webpage Lecture Four
11/8711 11
Writing a JavaScript Program
A JavaScript program can be placed anywhere within theHTML file.
Many programmers favor placing their programs between tags in order to separate the programming codefrom the Web page content and layout.
Some programmers prefer placing programs within the
body of the Web page at the location where the programoutput is generated and displayed.
-
7/31/2019 Webpage Lecture Four
12/8712 12
Using the Tag
To embed a client-side script in a Web page, use theelement:
script commands and comments
To access an external script, use:
script commands and comments
-
7/31/2019 Webpage Lecture Four
13/8713
Where to Put the JavaScript
There are three ways to add JavaScriptcommands to your Web Pages.
External file
Embedding code
Inline code
-
7/31/2019 Webpage Lecture Four
14/8714
Where to Put the JavaScript,External
You can use the SRC attribute of the tag tocall JavaScript code from an external text file.
This is useful if you have a lot of code or you want torun it from several pages, because any number of
pages can call the same external JavaScript file. The text file itself contains no HTML tags. It is call by
the following tag:
-
7/31/2019 Webpage Lecture Four
15/87
15
Where to Put the JavaScript, Embedding code
Scripts in
Scripts to be executed when they are called, or when an event istriggered, are placed in functions.
Put your functions in the head section, this way they are all in one place,and they do not interfere with page content.
function message(){alert("This alert box was called with the onload
event");
}
-
7/31/2019 Webpage Lecture Four
16/87
16
Where to Put the JavaScript, inline
Scripts in
If you don't want your script to be placed inside a function, or ifyour script should write page content, it should be placed in thebody section.
document.write("This message is written by JavaScript");
-
7/31/2019 Webpage Lecture Four
17/87
17 17
Comments
The syntax for a single-line comment is:// comment text
The syntax of a multi-line comment is:/*
comment text covering several lines*/
-
7/31/2019 Webpage Lecture Four
18/87
18 18
Hiding Script from Older Browsers
You can hide the script from these browsers usingcomment tags:
When a Web browser that doesnt support scripts
encounters this code, it ignores the tag.
-
7/31/2019 Webpage Lecture Four
19/87
19 19
Writing Output to a Web Page
JavaScript provides two methods to write text toa Web page:
document.write(text);
alert(message to display);
prompt(message to display);
document.write("News Flash!
"); -
7/31/2019 Webpage Lecture Four
20/87
20 20
JavaScript Syntax Issues
JavaScript commands and names are case-sensitive.
JavaScript command lines end with a semicolon toseparate it from the next command line in theprogram.
in some situations, the semicolon is optional
semicolons are useful to make your code easier tofollow and interpret
-
7/31/2019 Webpage Lecture Four
21/87
21
JavaScript Syntax Issues
Here are some tips to remember when writingJavaScript commands:
JavaScript code is case sensitive (e.g. age and Age
are different variables) White space between words and tabs are ignored
Line breaks are ignored except within a statement
JavaScript statements end with a semi colon (;)
-
7/31/2019 Webpage Lecture Four
22/87
22 22
Working with Variables & Data
A variable is a named element in a program that storesinformation. The following restrictions apply to variablenames:
the first character must be either a letter or anunderscore character ( _ )
the remaining characters can be letters, numbers, orunderscore characters
variable names cannot contain spaces
Variable names are case-sensitive.
document.write(Year);
-
7/31/2019 Webpage Lecture Four
23/87
23 23
Types of Variables
JavaScript supports four different types of variables:
numeric variables can be a number, such as 13, 22.5, or -3.14159
string variables is any group of characters, such as Helloor Happy Holidays!
Boolean variables are variables that accept one of twovalues, either true or false
null variables is a variable that has no value at all
-
7/31/2019 Webpage Lecture Four
24/87
24
Types of Variables In JavaScript, a value can be one of several types.
Table lists JavaScripts formal data types, withexamples of the values
Type Example Description
String John A series of characters inside quotation marks
Number 4.5 any number not inside quotes
Boolean True A logical true or false
Null Null completely devoid of any value
Object A software thing that is defined by its
properties and methods
-
7/31/2019 Webpage Lecture Four
25/87
25 25
Declaring a Variable
Before you can use a variable in your program, youneed to declare a variable using the var command orby assigning the variable a value.
Any of the following commands is a legitimate way ofcreating a variable named Month:
var Month;
Month = December;
var Month = December;
-
7/31/2019 Webpage Lecture Four
26/87
26 26
Working with Expressionsand Operators
Expressions are JavaScript commands that assignvalues to variables.
Expressions are created using variables, values, andoperators.
The + operator performs the action of adding or
combining two elements.
-
7/31/2019 Webpage Lecture Four
27/87
27
-
7/31/2019 Webpage Lecture Four
28/87
28
Assignment Operators
-
7/31/2019 Webpage Lecture Four
29/87
2929
Comparison, Logical, andConditional Operators
To create a condition, you need one of three types ofoperators:
a comparison operator compares the value of oneelement with that of another, which creates a Booleanexpression that is either true or false
a logical operator connects two or more Booleanexpressions
a conditional operator tests whether a specific condition
is true and returns one value if the condition is true and adifferent value if the condition is false
-
7/31/2019 Webpage Lecture Four
30/87
3030
An Example ofBoolean Expressions
x < 100;
if xis less than 100, this expression returns the value
true; however, if xis 100 or greater, the expression isfalse
y == 20;
the yvariable must have an exact value of 20 for the
expression to be true comparison operator uses a double equal sign (==)
-
7/31/2019 Webpage Lecture Four
31/87
3131
Comparison Operators
-
7/31/2019 Webpage Lecture Four
32/87
3232
A Logical Operator
The logical operator && returns a value of true only if all ofthe Boolean expressions are true.
-
7/31/2019 Webpage Lecture Four
33/87
3333
A Conditional Operator
Tests whether a specific condition is true and returns onevalue if the condition is true and a different value if thecondition is false.
Message = (mail == Yes) ? You have mail: Nomail;
tests whether the mailvariable is equal to the value Yes
if it is, the Messagevariable has the value You havemail;
otherwise, the Messagevariable has the value Nomail.
-
7/31/2019 Webpage Lecture Four
34/87
3434
Working with Conditional Statements
if (condition) {
JavaScript Commands
}
conditionis an expression that is either true or false
if the condition is true, the JavaScript Commandsin thecommand block are executed
if the condition is not true, then no action is taken
-
7/31/2019 Webpage Lecture Four
35/87
3535
Using an If...Else Statement
if (condition) {
JavaScript Commands if true
} else
JavaScript Commands if false}
conditionis an expression that is either true or false, andone set of commands is run if the expression is true, andanother is run if the expression is false
-
7/31/2019 Webpage Lecture Four
36/87
36
Using an If...Else Statement
If(mark>80)
status=excellent;
else if(mark>60)
status=very good;
else if(mark>50)
Status = fair;
else
status =poor;
-
7/31/2019 Webpage Lecture Four
37/87
37
Switch Statement
A switch statement allows a program to evaluate an expression
and attempt to match the expression's value to a case label. If a match is found, the program executes the associated
statement.
A switch statement looks as follows:switch (expression) {
case label1:statements1
[break;]
case label2:
statements2
[break;]
...
default:
statements default
[break;]
}
-
7/31/2019 Webpage Lecture Four
38/87
38
Example:
switch (fruittype) {case "Apples":
document.write("Apples are $0.32 a pound.
");break;
case "Bananas":
document.write("Bananas are $0.48 a pound.
");break;case "Mangoes":
case "Papayas":
document.write("Mangoes and papayas are $2.79 a
pound.
");break;default:
document.write("Sorry, we are out of " + fruittype +".
"); -
7/31/2019 Webpage Lecture Four
39/87
3939
Working with Program Loops
A program loop is a set of instructions that isexecuted repeatedly.
-
7/31/2019 Webpage Lecture Four
40/87
4040
The For Loop
The For loop allows you to create a group of commandsto be executed a set number of times through the use of a
counter that tracks the number of times the commandblock has been run.
Set an initial value for the counter, and each time thecommand block is executed, the counter changes in value.
When the counter reaches a value above or below acertain stopping value, the loop ends.
-
7/31/2019 Webpage Lecture Four
41/87
4141
The For Loop Continued
for (start; condition; update) {
JavaScript Commands
}
startis the starting value of the counter
conditionis a Boolean expression that must be true forthe loop to continue
updatespecifies how the counter changes in value eachtime the command block is executed
-
7/31/2019 Webpage Lecture Four
42/87
42
-
7/31/2019 Webpage Lecture Four
43/87
43
-
7/31/2019 Webpage Lecture Four
44/87
44
Specifying Counter Values in a For Loop
-
7/31/2019 Webpage Lecture Four
45/87
4545
The While Loop
The While loop runs a command group as long as aspecific condition is met, but it does not employ any
counters. The general syntax of the While loop is:
while (condition) {
JavaScript Commands
} conditionis a Boolean expression that can be either
true or false
-
7/31/2019 Webpage Lecture Four
46/87
46
-
7/31/2019 Webpage Lecture Four
47/87
47
C ti J S i t F ti
-
7/31/2019 Webpage Lecture Four
48/87
4848
Creating JavaScript Functions
Functions are one of the fundamental building blocks inJavaScript.
A function is a set of statements that performs a specific task.
To use a function, you must first define it; then your script cancall it.
functionfunction_name(parameters) {
JavaScript commands
}
parametersare the values sent to the function (note:not all functions require parameters)
{ and } are used to mark the beginning and end of thecommands in the function.
-
7/31/2019 Webpage Lecture Four
49/87
4949
Creating JavaScript Functions
Function names are case-sensitive.
The function name must begin with a letter or underscore (
_ ) and cannot contain any spaces. There is no limit to the number of function parameters that
a function may contain.
The parameters must be placed within parentheses,
following the function name, and the parameters must beseparated by commas.
-
7/31/2019 Webpage Lecture Four
50/87
5050
Performing an Action with a Function
Example: the following code defines a simplefunction named square:
function square(number) {return number * number;
}
There is one line in the functions command block, which
return square of a number
-
7/31/2019 Webpage Lecture Four
51/87
5151
Returning a Value from a Function
To use a function to calculate a value use the returncommand along with a variable or value.
function Area(Width, Length){
var Size = Width*Length;return Size;
}
document.write(Area(4,3)); the Area function calculates the area of a rectangular
region and places the value in a variable named Size
the value of the Size variable is returned by the function
A
-
7/31/2019 Webpage Lecture Four
52/87
52
Arrays
Just think of an example where you want tostore 100 different names.
How could you do this with JavaScript? Well,you could define 100 variables and assign thedifferent names to them.
This is quite complicated and tiresome.
This can be solved with arrays which can be
seen as many variables bundled together.
-
7/31/2019 Webpage Lecture Four
53/87
5353
Using Arrays
An array is an ordered collection of values referenced by asingle variable name.
The syntax for creating an array variable is:
var variable= new Array(size); variableis the name of the array variable
sizeis the number of elements in the array (optional)
To populate the array with values, use:
variable[i]=value;where i is the ith item of the array. The 1st item has anindex value of 0.
-
7/31/2019 Webpage Lecture Four
54/87
5454
Using Arrays
To create and populate the array in a singlestatement, use:
var variable= new Array(values);
valuesare the array elements enclosed inquotes and separated by commas
var MonthTxt=new Array(, January,February, March, April, May, June,
July, August, September, October,November, December);
January will have an index value of 1.
MonthTxt[1];
Using Arrays
-
7/31/2019 Webpage Lecture Four
55/87
55
Deleting Array Entries Deleting an array element eliminates the index from the list of
accessible index values but does not reduce the arrays length.
MonthTxt.length; // result: 13
delete MonthTxt [2];
MonthTxt.length; //result: 13
MonthTxt[2]; //result: undefined array.concat(array2)
The array.concat() method allows you to join two array objects into anew, third array object.
var array1 = new Array(a,b)
var array2 = new Array(c,d,e)
var array3 = array1.concat(array2)
// result: array with values a,b,c,d,e
Using Arrays
Arra Object Methods
-
7/31/2019 Webpage Lecture Four
56/87
56
Array Object Methods
array.sort([compareFunction])
This methods returnsarray of entries in theorder as determined by
the compareFunctionalgorithm.
Return
Value
Range
Meaning
< 0 value b should sort later
than a
0 The order of a and b
should not change
> 0 Value a should sort later
than b
Example: a function that sorts numbers
myArray = new Array(12, 5, 200, 80)
function compare(a,b) {
return a - b;
}
myArray.sort(compare);
Other Array Object Methods
-
7/31/2019 Webpage Lecture Four
57/87
57
Method Description
every() Returns true if every element in this array satisfies the provided testing function.
filter() Creates a new array with all of the elements of this array for which the provided
filtering function returns true.
forEach() Calls a function for each element in the array.
indexOf(value) Returns the first (least) index of an element within the array equal to the specified
value, or -1 if none is found.
join(separator) Joins all elements of an array into a string using separator
lastIndexOf(value) Returns the last (greatest) index of an element within the array equal to the
specified value, or -1 if none is found.
pop() Removes the last element from an array and returns that element.
push(value) Adds one or more elements to the end of an array and returns the new length of
the array.
reverse() Reverses the order of the elements of an array the first becomes the last, and the
last becomes the first.
shift() Removes the first element from an array and returns that element.
slice(start [,end]) Extracts a section of an array and returns a new array.
splice(start, count) Adds and/or removes elements from an array.
toString() Returns a string representing the array and its elements.
unshift(value) Adds one or more elements to the front of an array and returns the new length ofthe array.
Example: Some Array Functions
-
7/31/2019 Webpage Lecture Four
58/87
58
javascript test
function arrayFunction() {
var grade = new Array("70", "60", "80", "90", "20");document.write("
Popped: " + grade.pop());document.write("
After poping:");for(var i=0;i -
7/31/2019 Webpage Lecture Four
59/87
59
Working with JavaScript Objects
JavaScript has many built-in objects that youcan use to perform different activities.
The most important objects are discussed next.
-
7/31/2019 Webpage Lecture Four
60/87
6060
The Math Object & Math Methods
Another way of performing a calculation is to use theJavaScript built-in Math methods.
These methods are applied to an object called the Math
object. The syntax for applying a Math method is:
value=Math.method(variable); For example,
AbsValue = Math.abs(NumVar);
The Math Object & Math Methods
-
7/31/2019 Webpage Lecture Four
61/87
61
The Math Object & Math Methods
The predefined Math object has properties and
methods for mathematical constants and functions. For example, the Math objects PI property has the
value of pi (3.141...), which you would use in anapplication as
Math.PI Similarly, standard mathematical functions are
methods of Math. These include trigonometric, logarithmic, exponential, and
other functions.
For example, if you want to use the trigonometric function sine,you would write:
Math.sin(1.56)
Note that all trigonometric methods of Math take
arguments in radians.
Math Object Properties
-
7/31/2019 Webpage Lecture Four
62/87
62
Math Object Properties
Property Value Description
Math.E 2.718281828459045091 Eulers constant
Math.LN2 0.6931471805599452862 Natural log of 2
Math.LN10 2.302585092994045901 Natural log of 10
Math.LOG2E 1.442695040888963387 Log base-2 of E
Math.LOG10E 0.4342944819032518167 Log base-10 of E
Math.PI 3.141592653589793116
Math.SQRT1_2 0.7071067811865475727 Square root of 1/2
Math.SQRT2 1.414213562373095145 Square root of 2
-
7/31/2019 Webpage Lecture Four
63/87
63
Example:
-
7/31/2019 Webpage Lecture Four
64/87
64
Example:
Math.floor(1.6); //result: 1
Math.ceil(1.6); //result: 2 exp (x): returns the exponential function of x (e raised
to the power of x, where e is the base of the naturallogarithms). Math.exp(3);
log (x): returns the natural logarithm of x. Math.log(20);
Math.pow(5,2); //output: 25
Math.round(3.5); // output: 4
Math.round(3.5); //output:3. Max(2,3);// output: 3.
Min(2,3);// output: 2.
Working with Dates
-
7/31/2019 Webpage Lecture Four
65/87
65
Working with Dates
Most of your date and time work is done withthe Date object.
The basic syntax for generating a new dateobject is as follows:
var dateObjectName = new Date([parameters]) The parameter can be:
new Date(Month dd, yyyy hh:mm:ss)
new Date(Month dd, yyyy)
new Date(yy,mm,dd,hh,mm,ss)
new Date(yy,mm,dd)
new Date(milliseconds)
R t i i th D & Ti V l
-
7/31/2019 Webpage Lecture Four
66/87
6666
Retrieving the Day & Time Values
JavaScript stores dates and times as the number ofmilliseconds since 6 p.m on 12/31/69.
Use built in JavaScript date methods to do calculations.
If you want the ThisDay variable to store the day of the month. To get that information, apply the getDate() method.
DayValue= DateObject.getDate()
The getMonth() method extracts the value of the current month.
JavaScript starts counting months with 0 for January, you may wantto add 1 to the month number returned by the getMonth() method.
ThisMonth= Today.getMonth()+1;
The getFullYear() method extracts the year value from the datevariable.
ThisYear = Today.getFullYear();
Method Value Range Description
dateObj getTime() 0- returns Milliseconds since 1/1/70 00:00:00 GMT
-
7/31/2019 Webpage Lecture Four
67/87
67
dateObj.getTime() 0 ... returns Milliseconds since 1/1/70 00:00:00 GMT
dateObj.getYear() 70-... returns Specified year minus 1900
returns four-digit year for 2000+
dateObj.getFullYear() 1970-... returns four-digit year (Y2K-compliant)
dateObj.getMonth() 0-11 returns Month within the year (January = 0)
dateObj.getDate() 1-31 returns Date within the month
dateObj.getDay() 0-6 returns Day of week (Sunday = 0)
dateObj.getHours() 0-23 returns Hour of the day in 24-hour time
dateObj.getMinutes() 0-59 returns Minute of the specified hour
dateObj.getSeconds() 0-59 returns Second within the specified minute
dateObj.setTime(val) 0-... sets Milliseconds since 1/1/70 00:00:00 GMT
dateObj.setYear(val) 70-... sets Specified year minus 1900
sets four-digit year for 2000+
dateObj.setMonth(val) 0-11 sets Month within the year (January = 0)
dateObj.setDate(val) 1-31 sets Date within the month
dateObj.setDay(val) 0-6 sets Day of week (Sunday = 0)
dateObj.setHours(val) 0-23 sets Hour of the day in 24-hour time
dateObj.setMinutes(val) 0-59 sets Minute of the specified hour
dateObj.setSeconds(val) 0-59 sets Second within the specified minute
Date Examples
-
7/31/2019 Webpage Lecture Four
68/87
68
Date Examples
var d=new Date();
document.write(d);
Sat Mar 24 2012 10:38:47 GMT-0700 (Pacific DaylightTime)
Date Examples
-
7/31/2019 Webpage Lecture Four
69/87
69
Date Examples
Example: to set date to some past time like
birth date
myBirthday = new Date(September 11, 2001)
result = myBirthday.getDay() // result = 2, a TuesdaymyBirthday.setYear(2002) // bump up to next year
result = myBirthday.getDay() // result = 3, aWednesday
-
7/31/2019 Webpage Lecture Four
70/87
Date Examples
-
7/31/2019 Webpage Lecture Four
71/87
71
Click the button to display todays day of the
week.
Try it
function myFunction(){
var d = new Date();
var weekday=new Array(7);weekday[0]="Sunday";weekday[1]="Monday";weekday[2]="Tuesday";
weekday[3]="Wednesday";weekday[4]="Thursday";
weekday[5]="Friday";weekday[6]="Saturday";
var x = document.getElementById("demo");x.innerHTML=weekday[d.getDay()];
}
String Object
-
7/31/2019 Webpage Lecture Four
72/87
72
String Object The syntax to define string object is:
var stringVar = new String(characters);
Example:var name = new String(Konrad Zuse);
name.concat( - created the first computer);
name.substring(0,10);name.indexOf(Zuse);name.replace(a,#);name.toUpperCase();
Output:Konrad Zuse - created the first computer
Konrad Zuse7
Konr#d ZuseKONRAD ZUSE
Method Description
charAt() Returns the character at the specified index
http://www.w3schools.com/jsref/jsref_charat.asphttp://www.w3schools.com/jsref/jsref_charat.asp -
7/31/2019 Webpage Lecture Four
73/87
73
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a copy of the joined strings
fromCharCode() Converts Unicode values to characters
indexOf() Returns the position of the first found occurrence of a specified value in astring
lastIndexOf() Returns the position of the last found occurrence of a specified value in astring
match() Searches for a match between a regular expression and a string, and returnsthe matches
replace() Searches for a match between a substring (or regular expression) and astring, and replaces the matched substring with a new substring
search() Searches for a match between a regular expression and a string, and returnsthe position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
substr() Extracts the characters from a string, beginning at a specified start position,and through the specified number of character
substring() Extracts the characters from a string, between two specified indices
toLowerCase() Converts a string to lowercase letters
toUpperCase() Converts a string to uppercase letters
valueOf() Returns the primitive value of a String object
Example
http://www.w3schools.com/jsref/jsref_valueof_string.asphttp://www.w3schools.com/jsref/jsref_charcodeat.asphttp://www.w3schools.com/jsref/jsref_concat_string.asphttp://www.w3schools.com/jsref/jsref_fromcharcode.asphttp://www.w3schools.com/jsref/jsref_indexof.asphttp://www.w3schools.com/jsref/jsref_lastindexof.asphttp://www.w3schools.com/jsref/jsref_match.asphttp://www.w3schools.com/jsref/jsref_replace.asphttp://www.w3schools.com/jsref/jsref_search.asphttp://www.w3schools.com/jsref/jsref_slice_string.asphttp://www.w3schools.com/jsref/jsref_split.asphttp://www.w3schools.com/jsref/jsref_substr.asphttp://www.w3schools.com/jsref/jsref_substring.asphttp://www.w3schools.com/jsref/jsref_tolowercase.asphttp://www.w3schools.com/jsref/jsref_touppercase.asphttp://www.w3schools.com/jsref/jsref_valueof_string.asphttp://www.w3schools.com/jsref/jsref_valueof_string.asphttp://www.w3schools.com/jsref/jsref_touppercase.asphttp://www.w3schools.com/jsref/jsref_tolowercase.asphttp://www.w3schools.com/jsref/jsref_substring.asphttp://www.w3schools.com/jsref/jsref_substr.asphttp://www.w3schools.com/jsref/jsref_split.asphttp://www.w3schools.com/jsref/jsref_slice_string.asphttp://www.w3schools.com/jsref/jsref_search.asphttp://www.w3schools.com/jsref/jsref_replace.asphttp://www.w3schools.com/jsref/jsref_match.asphttp://www.w3schools.com/jsref/jsref_lastindexof.asphttp://www.w3schools.com/jsref/jsref_indexof.asphttp://www.w3schools.com/jsref/jsref_fromcharcode.asphttp://www.w3schools.com/jsref/jsref_concat_string.asphttp://www.w3schools.com/jsref/jsref_charcodeat.asp -
7/31/2019 Webpage Lecture Four
74/87
74
Example
var txt = "Hello World!";
document.write(txt.length+ "
");document.write(txt.indexOf("o") + "
");document.write(txt.match("world") + "
");document.write(txt.match("World") + "
");document.write(txt.substring(0,10)+ "
");document.write(txt.replace("e","n")+ "
");document.write(txt.toUpperCase()+ "
");String HTML Wrapper Methods The HTML wrapper methods return the string wrapped inside the
-
7/31/2019 Webpage Lecture Four
75/87
75
The HTML wrapper methods return the string wrapped inside theappropriate HTML tag.
Method Description
anchor()
Creates an anchor
big() Displays a string using a big font
blink() Displays a blinking string
bold() Displays a string in bold
fixed() Displays a string using a fixed-pitch font
fontcolor()
Displays a string using a specified color
fontsize()
Displays a string using a specified size
italics() Displays a string in italic
link() Displays a string as a hyperlink
small() Displays a string using a small font
strike() Displays a string with a strikethrough
sub() Displays a string as subscript text
sup() Displays a string as superscript text
Example
http://www.w3schools.com/jsref/jsref_anchor.asphttp://www.w3schools.com/jsref/jsref_anchor.asphttp://www.w3schools.com/jsref/jsref_big.asphttp://www.w3schools.com/jsref/jsref_blink.asphttp://www.w3schools.com/jsref/jsref_bold.asphttp://www.w3schools.com/jsref/jsref_fixed.asphttp://www.w3schools.com/jsref/jsref_fontcolor.asphttp://www.w3schools.com/jsref/jsref_fontcolor.asphttp://www.w3schools.com/jsref/jsref_fontsize.asphttp://www.w3schools.com/jsref/jsref_fontsize.asphttp://www.w3schools.com/jsref/jsref_italics.asphttp://www.w3schools.com/jsref/jsref_link.asphttp://www.w3schools.com/jsref/jsref_small.asphttp://www.w3schools.com/jsref/jsref_strike.asphttp://www.w3schools.com/jsref/jsref_sub.asphttp://www.w3schools.com/jsref/jsref_sup.asphttp://www.w3schools.com/jsref/jsref_sup.asphttp://www.w3schools.com/jsref/jsref_sub.asphttp://www.w3schools.com/jsref/jsref_strike.asphttp://www.w3schools.com/jsref/jsref_small.asphttp://www.w3schools.com/jsref/jsref_link.asphttp://www.w3schools.com/jsref/jsref_italics.asphttp://www.w3schools.com/jsref/jsref_fontsize.asphttp://www.w3schools.com/jsref/jsref_fontsize.asphttp://www.w3schools.com/jsref/jsref_fontcolor.asphttp://www.w3schools.com/jsref/jsref_fontcolor.asphttp://www.w3schools.com/jsref/jsref_fixed.asphttp://www.w3schools.com/jsref/jsref_bold.asphttp://www.w3schools.com/jsref/jsref_blink.asphttp://www.w3schools.com/jsref/jsref_big.asphttp://www.w3schools.com/jsref/jsref_anchor.asphttp://www.w3schools.com/jsref/jsref_anchor.asp -
7/31/2019 Webpage Lecture Four
76/87
76
var txt = "Hello World!";
document.write("
Big: " + txt.big() + "
");document.write("
Small: " + txt.small() + "
");document.write("
Bold: " + txt.bold() + "
");document.write("
Italic: " + txt.italics() + "
");document.write("
Fixed: " + txt.fixed() + "
");document.write("Strike: " + txt.strike() + "
");document.write("
Fontcolor: " + txt.fontcolor("green") + "
");document.write("
Fontsize: " + txt.fontsize(6) + "
");document.write("
Subscript: " + txt.sub() + "
");document.write("
Superscript: " + txt.sup() + "
");document.write("Link: " + txt.link("http://www.w3schools.com") +
"
");document.write("
Blink: " + txt.blink() + " (does not work in IE,Chrome, or Safari)
");Document Object
-
7/31/2019 Webpage Lecture Four
77/87
77
Contains information on the current document.
Document object contains properties andmethods that can be used to access the page
elements.
History Object
-
7/31/2019 Webpage Lecture Four
78/87
78
History Object
The history object contains a list of strings representing the URLs
the client has visited. You can access the current, next, and previous history entries by
using the history objects current, next, and previous properties.
You can access the other history values using the history array.
This array contains an entry for each history entry in source order;
each array entry is a string containing a URL. You can also redirect the client to any history entry by using the go
method.
For example, the following code loads the URL that is two entriesback in the clients history list.
history.go(-2)
The following code reloads the current page:
history.go(0)
History Object
-
7/31/2019 Webpage Lecture Four
79/87
79
History Object
Properties Methods
Current back()
Length forward()
Next go()
Previous
history.back() goes back to last visited page
history.forward() goes forward just like clicking
forward button on toolbar
history.go(location) goes to the specified history
location
-
7/31/2019 Webpage Lecture Four
80/87
Event Event Handler Description
Load onLoad Browser finishes loading a Web document
-
7/31/2019 Webpage Lecture Four
81/87
81
Unload onUnload Visitor requests a new document in the browser window
Mouseover onMouseOver Visitor moves the mouse over some object in the document window
Mouseout onMouseOut Visitor moves the mouse off of some object in the document window
MouseDown onMouseDown A mouse button was pressedMouseMove onMouseMove The mouse moved
MouseUp onMouseUp The mouse button was released
Select onSelect Text has been selected.
Click onClick Visitor clicks the mouse button
Focus onFocus Visitor gives focus to or makes active a particular window or form element by
clicking on it with a mouse or other pointing device or tabbing to it
Blur onBlur A form field lost the focus (user moved to another field)
Change onChange Visitor changes the data selected or contained in a form element
Submit onSubmit Visitor submits a form
Reset onReset Visitor resets a form
Abort onAbort An image failed to load
Change onChange The contents of a field has changed
DblClick onDblClick User double-clicked on this item
Error onError An error occurred while loading an image
Keydown onKeyDown A key was pressed
KeyPress onKeyPress A key was pressed OR released
Ke UP onKe U A ke was released
Example
-
7/31/2019 Webpage Lecture Four
82/87
82
function adder(num1, num2) {
var sum = 0;sum = num1 + num2;
document.write("The sum is " + sum); }function subtractor(num1, num2) {
var difference = 0;difference = num1 - num2;document.write("The difference is " + difference); }
Form Processing and Validation
-
7/31/2019 Webpage Lecture Four
83/87
83
Form Processing and Validation
Forms are widely used on the Internet.
The form input is often sent back to the server ormailed to a certain e-mail account.
But how can you be certain that a valid input was filledby the user?
With the help of JavaScript the form input can easily be
checked before sending it over the Internet. It is sent only if the input is valid.
Form data that typically are checked by a JavaScriptcould be:
has the user left required fields empty? has the user entered a valid e-mail address?
has the user entered a valid date?
has the user entered text in a numeric field?
ExampleFi t f ll t HTML th t t i f
-
7/31/2019 Webpage Lecture Four
84/87
84
First of all we create an HTML-page that contains form. The form contains three text inputs, a text area, and a button. The user has to write his name into the first, age in the second, an
e-mail address in the third text fields, and message in the textarea.
In the name field, you will receive an error message whennothing is entered. The browser even accepts numbers.
So if you enter '17' you will get 'Hi 17!'. So this might not be a good
check in this particular example. However, you can add a check fornumbers in the name field and reject the name if you like.
Age is number and we expect a positive number only. If user enters characters which are not number, or negative value,
it is not valid age. So the script should check this and determine itsvalidity.
The email field is a little bit more sophisticated. It shouldnt work if there is no @ symbol in the email because
valid email addresses contain that symbol. The criteria for accepting the input as a valid e-mail address is the @.
The person may enter wrong emails which could pass as valid but thisis the least check we could do.
Example
-
7/31/2019 Webpage Lecture Four
85/87
85
a p e
function check(form)
-
7/31/2019 Webpage Lecture Four
86/87
86
( ){ if (form.urname.value == "")alert("Please enter a string as your name!")
elsealert("Hi " + form.urname.value + "! Name ok!");
if(form.age.value < 0 || form.age.value=="")alert("Age should be number and greater than 0");
elsealert("Age ok");
if (form.email.value == "" || form.email.value.indexOf('@', 0) == -1)alert("No valid e-mail address!");
elsealert("Email oK!");if(form.urmessage.value=="")
alert("No message written");else
alert("Message ok"); }
Form validation
Enter your name:
Enter your age:Enter your e-mail address:
write message:
JavaScript Popup Boxes
function disp alert(){
-
7/31/2019 Webpage Lecture Four
87/87
function disp_alert(){alert("Hello again! This is how we" + '\n' + "add line breaks to an
alert box!");}function show_prompt(){
var name=prompt("Please enter your name","Harry Potter");if (name!=null && name!="") {
document.write("
Hello " + name + "! How are you today?
");}}function show_confirm(){var r=confirm("Press a button!");
if (r==true) {alert("You pressed OK!"); }
else {alert("You pressed Cancel!");
}}