Chapter 3 JavaScript
Chapter 3 JavaScript
JAVASCRIPT
• What is JavaScript?
– JavaScript: the first Web scripting language,
Client side programming developed by Netscape in 1995 syntactic
similarities to Java/C++,
• but simpler & more flexible
• (loose typing, dynamic variables, simple objects)
JavaScript – An object-oriented scripting language that is
designed primarily for people who are building web
pages using HTML.
3 4
1
11/16/2017
5 6
Introduction to JavaScript
• Javascript is object-oriented. • When to use JavaScript?
– Data entry validation
– It allows interaction with the properties of • If form fields need to be filled out for processing on the
objects that it recognizes. server, I let clientside scripts prequalify the data
entered by the user.
• Internal built-in objects (e.g. window object).
– Dynamic HTML interactivity.
• Browser objects (e.g. document object).
• if you intend to make the content dance on the page,
scripting makes that happen.
– CGI prototyping
• Sometimes you want a CGI program to be at the root of
your application because it reduces the potential
incompatibilities among browser brands and versions.
• Use this opportunity to polish the user interface before
implementing the application as a CGI.
7
2
11/16/2017
• Javascript is a small language and does not JavaScript code can be embedded in a Web page using SCRIPT tags
◦ the output of JavaScript code is displayed as if directly entered in
have many features that exist in Java. HTML
• Java is a powerful language and can be used in [Link] displays text in page text to be displayed can
include HTML tags
extremely sophisticated applications. the tags are interpreted by the browser when the text is displayed
as in C++/Java, statements end with ; but it Optional
JavaScript comments similar to C++/Java
◦ // starts a single line comment
◦ /*…*/ enclose multi-line comments
11 12
3
11/16/2017
13 14
15 16
4
11/16/2017
17 18
19 20
5
11/16/2017
Properties Methods
• Properties are object attributes. • Methods are actions applied to particular
objects.
• Object properties are defined by using the
object's name, a period, and the property • Methods are what objects can do.
name. – e.g., [Link](”Hello
World")
– e.g., background color is expressed by:
• document is the object.
[Link] .
• write is the method.
– document is the object.
– bgcolor is the property.
21 22
[Link](“String”) [Link](“String”)
<HTML>
<HEAD><TITLE>Hello!</TITLE></HEAD>
<BODY>
<H1> First JavaScript Page </H1>
<SCRIPT TYPE="text/javascript">
/* --->
----- */
[Link]("<HR/>");
[Link]("Hello WWW!");
[Link]("<HR/>");
//-->
</SCRIPT>
</BODY>
</HTML>
23 24
6
11/16/2017
Events…
Events • JavaScript is event-driven.
– Something has to happen before the JavaScript is
• Events associate an object with an action. executed.
• JavaScript defines various events:
– e.g., the OnMouseover event handler action can
– onClick – link or image is clicked
change an image.
– onSubmit – a form is submitted
– e.g., the onSubmit event handler sends a form. – onMouseOver – the mouse cursor moves over it
• User actions trigger events. – onChange – a form control is changed
– onLoad – something gets loaded in the browser
– etc.
– Events are specified in the HTML code.
25 26
Event example
<html> Functions
<head>
<script language=“javascript”> • Functions are named statements that
function funct() {
performs tasks.
// code
} – e.g., function doWhatever ()
</script> {statement here}
</head> – The curly braces contain the statements of the
<body> function.
<img src=“[Link]” > </body>
• JavaScript has built-in functions, and you can
</html> write your own.
NB: Language=“JavaScript” is optional.
27 28
7
11/16/2017
Values Variables
• Values are bits of information. • Variables contain values and use the equal
• Values types and some examples include: sign to specify their value.
– Number: 1, 2, 3, etc. • Variables are created by declaration using the
– String: characters enclosed in quotes. var command with or without an initial value
– Boolean: true or false. state.
– Object: image, form – e.g. var month;
– Function: validate, doWhatever – e.g. var month = April;
– e.g. month = April;
29 30
31 32
8
11/16/2017
33 34
9
11/16/2017
Alert Box
Syntax
• alert("sometext");
37 38
Prompt Box
Example
<html> • A prompt box is often used if you want the user
<head>
<script type="text/javascript"> to input a value before entering a page.
function show_alert()
{
• When a prompt box pops up, the user will have
alert("I am an alert box!"); to click either "OK" or "Cancel" to proceed after
} entering an input value.
</script>
</head> • If the user clicks "OK" the box returns the input
<body> value. If the user clicks "Cancel" the box returns
<input type="button" value="Show alert null.
box" /> • Syntax
</body> • prompt("sometext","defaultvalue");
</html>
39 40
10
11/16/2017
Example 1 Example 2
<html> <html>
<head> <head>
<script type="text/javascript">
function show_prompt() <title>Interactive page</title>
{ </head>
var name=prompt("Please enter your name",“Abebe Tesema ");
if (name!=null && name!="") <body>
{ <script type="text/javascript">
[Link]("Hello " + name + "! How are you today?"); userName = prompt("What is your name?", "");
} userAge = prompt("Your age?", "");
} userAge = parseFloat(userAge);
</script> [Link]("Hello " + userName + ".")
</head>
<body> if (userAge < 18) {
[Link](" Do your parents know " + "you are online?");
}
<input type="button" value="Show
prompt box" /> </script>
<p>The rest of the page...
</body> </body>
</html> </html>
41 42
43 44
11
11/16/2017
Example
Example <html>
<head>
<script type="text/javascript">
function show_confirm()
• Simple event handler with a confirm box. {
var r=confirm("Press a button");
if (r==true)
<SCRIPT> {
alert("You pressed OK!");
function respond() }
else
{ {
confirm (“Hello there!”); alert("You pressed Cancel!");
}
} }
</script>
</SCRIPT> </head>
<body>
<H2>Click on the following button</H2>
<FORM> <input type="button" value="Show confirm box" />
47 48
12
11/16/2017
49 50
51 52
13
11/16/2017
The following function displays a message with the current date: To call the ShowDate function, enter:
function ShowDate(date) { var Today = “3/9/2010”;
[Link](“Today is” + date + “<br>”); ShowDate(Today);
} – the first command creates a variable named “Today” and
assigns it the text string, “3/9/2010”
– there is one line in the function’s command block, which
displays the current date along with a text string – the second command runs the ShowDate function, using the
value of the Today variable as a parameter
– result is “Today is 3/9/2010”
53 54
55 56
14
11/16/2017
57 58
• x < 100;
– if x is less than 100, this expression returns the value true;
however, if x is 100 or greater, the expression is false
• y == 20;
– the y variable must have an exact value of 20 for the
expression to be true
– comparison operator uses a double equal sign (==)
59 60
15
11/16/2017
61 62
Today is 12/08/2010
Only 17 days until Christmas
63
16
11/16/2017
• A program loop is a set of instructions that is • The For loop allows you to create a group of commands to be
executed repeatedly. executed a set number of times through the use of a counter
that tracks the number of times the command block has been
• There are two types of loops: run.
– loops that repeat a set number of times before • Set an initial value for the counter, and each time the
quitting command block is executed, the counter changes in value.
– loops that repeat as long as a certain condition is • When the counter reaches a value above or below a certain
stopping value, the loop ends.
met
65 66
67
17
11/16/2017
71
18
11/16/2017
Using Arrays
74
75 76
19
11/16/2017
• In the object-oriented paradigm, methods • Methods which are defined on an object give
refer to functions that can be used to the range of choices available for interacting
manipulate objects and their properties. with the object. Some examples:
– Example: The method write(), which when – A window object can be opened or closed using
invoked on the document object, causes a specific the open() and close() methods respectively.
string of characters to be outputted. – A form object has a submit() method which
• [Link] (“Hello Good Day”); transmits the contents of the form to the web
server.
77 78
Data validation
The sequential list of a user’s path through a number • Javascript can be used for client-side
of URLs is represented by the history object, which
has forward() and backward()methods to move
validation of data entered in HTML forms.
through the list. – Data entered can be extracted and accessed.
Apart from the pre-defined methods, it is also – Checks can be made on the data entered.
possible to create user-defined methods. • Non-alphabetic characters in name.
◦ Control the rate with which a line of text scrolls • Non-numeric characters in roll number, age, etc.
across the screen. • Bid amount less than minimum permissible.
◦ Determine the path of an animated object across
the display.
79 80
20
11/16/2017
Example
<SCRIPT LANGUAGE="JavaScript">
function validRoll (theField) // parameter object
{
• A data validation example: var nsize = [Link];
– A student registration form. var nval = [Link];
var valid = true;
– A function checks whether the roll number is a 7- for (var i=0; i<7; i++)
digit numeric value. {
var nxtchar = [Link] (i,i+1);
• Invoked when the form is submitted.
//extracts the characters in a string between "from" and "to", not
• Check performed before form data are transmitted to including "to" itself.
server-side CGI script. if (nxtchar < "0" || nxtchar > "9")
valid = false; }
if (valid == false)
alert ("Invalid roll number: " + nval); }
</SCRIPT>
81 82
83 84
21
11/16/2017
85 86
function slow()
History Back / Forward
{
delay = delay + 25;
if (delay > 2000) delay = 2000; • Use the history object.
}
function fast()
{
– Call the back() and forward() methods to scroll
delay = delay - 25; through the recently visited pages.
if (delay < 0) delay = 0;
}
</SCRIPT>
<BODY>
<IMG NAME="line_rotate" SRC="[Link]"
('animate()', delay)" >
<FORM>
<INPUT TYPE="button" VALUE="Slow"
>
<INPUT TYPE="button" VALUE="Fast"
>
</FORM>
</BODY>
87 88
22
11/16/2017
89 90
91 92
23
11/16/2017
93 94
24
11/16/2017
97 98
Using Cookies
• JavaScript provides some limited, persistent storage, called
cookies:
Advantages: – A cookie is a small amount of named data stored by the
web browser and is associated with a particular web page
◦ Less code has to be written, and stored. or web site.
◦ Commonly used Javascript code can be shared – Serves to give the web browser the capability to
among a number of pages. memorize something.
– By default, cookies are destroyed when the browser
Only a single copy needs to be stored on the web server.
window is closed, unless you explicitly set the expires
◦ Such Javascript files can be cached by the browser, attribute.
thereby allowing faster loading of the pages. • To persist a cookie, set the expires attribute to a
future date.
◦ The URL specified in the src attribute can refer to
• To delete a cookie, set the expires attribute to a past
other web servers also. date.
99 100
25
11/16/2017
Cookies….
Javascript can manipulate cookies using the
“cookie” property of the “document” object. ◦ In addition to a name and value, each cookie has
◦ It is a string property that allows one to read, optional attributes:
create, modify, and delete cookies associated expires : specifies the cookie’s lifetime.
with the current web page. path : web pages with which it is associated.
• secure : a Boolean value; if set, cookies are transmitted
• In simple terms, we create a cookie like this:
using HTTPS.
[Link] = "name=value; expires=date;
– If the "secure" parameter is set, the cookie can only be sent to
path=path; domain=domain; secure"; a Secure Sockets Layer (SSL) server which would have a URL
...and retrieve all our previously set cookies like this: like: [Link]
It uses "HTTPS" for the protocol rather than "HTTP".
var x = [Link];
101 102
103 104
26
11/16/2017
105 106
String Object
• The String Object
• JavaScript supports the following built-in language objects: • Is one of the highest-level language objects in the
JavaScript object hierarchy.
• The String object • Can be created by assigning a string value to a
• The Array object variable or a property.
• The Date object • JavaScript’s string and character-processing
• The Math object capabilities
• Appropriate for processing names, addresses,
credit card information, etc.
– Characters
• Fundamental building blocks of JavaScript
programs
– String
107 • Series of characters treated as a single unit 108
27
11/16/2017
getDay() Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the week in local time or UTC,
getUTCDay() respectively.
manipulations getHours()
getUTCHours()
Returns a number from 0 to 23 representing hours since midnight in local time or UTC, respectively.
and time. getMinutes() Returns a number from 0 to 59 representing the minutes for the time in local time or UTC, respectively.
getUTCMinutes()
getMonth() Returns a number from 0 (January) to 11 (December) representing the month in local time or UTC,
getUTCMonth() respectively.
getSeconds() Returns a number from 0 to 59 representing the seconds for the time in local time or UTC, respectively.
getUTCSeconds()
getTime() Returns the number of milliseconds between January 1, 1970 and the time in the Date object.
getTimezoneOffset() Returns the difference in minutes between the current time on the local computer and UTC—previously
known as Greenwich Mean Time (GMT).
setDate( val ) Sets the day of the month (1 to 31) in local time or UTC, respectively.
setUTCDate( val )
111 112
28
11/16/2017
setSeconds( s, ms ) Sets the second in local time or UTC, respectively. The second argument
setUTCSeconds( s, ms )
representing the milliseconds is optional. If this argument is not specified, the
current millisecond value in the Date object is used.
113 114
115 116
29
11/16/2017
30
11/16/2017
31
11/16/2017
32
11/16/2017
33
11/16/2017
34
11/16/2017
35
11/16/2017
36
11/16/2017
37
11/16/2017
Exercises
• Develop a page with student registration form
and display the information on another page
• Develop a page with a registration form for a
company and displays the information as a Strings, Math and Dates
table using a pop-up windows
38
11/16/2017
String String
• To create a string object • String methods
var hello = “Howdy” var result = [Link]();
– Change case
var hello = new String(“Howdy”)
var result = [Link]();
• Joining Strings var result = [Link]();
String Math
• String methods • Most common functions are:
var – var piVal = [Link]
• Returns the char at index within str – var larger = [Link](val1, val2)
var subStr = [Link](startIndex, endindex) – var result = [Link](val1, powVal)
• Returns the substring from strartIndex (inclusive) to – var int = [Link](floatVal)
endIndex (exclusive)
– var ran = [Link]()
• Exercise:
– var smallInt = [Link](floatVal)
– Find out some other string methods
• Exercise:
– Find out some more Math methods
39
11/16/2017
Date Date
• To create an instance of the PC’s clock • Date calculations
var today = new Date();
– The surest way is to convert all dates to
• To get an instance of the PC’s clock at a specified miliseconds and perform the operation
date or time
var someday = new Date(“date or time”); var todayInMS = [Link]();
• To extract time, date or day from the already created var nextWeekInMS = todayInMS + (60 * 60 * 24 * 7
instance * 1000);
var result = [Link](),
= [Link]()
= [Link]()
• More from table 10-1
Exercise
• Develop online calculator
• Develop an online application that takes a
date (yy,mm,dd) and returns the day (Mon,
Tue…..)
• Attach a clock to your website
• Do some more exercises on input/output,
Interaction with the user
40