JAVA SCRIPT
INTRODUCTION OF JAVA SCRIPT
A scripting language is a lightweight programming
language.
JavaScript is programming code that can be
inserted into HTML pages.
JavaScript inserted into HTML pages, can be
executed by all modern web browsers.
JavaScript is easy to learn.
▪ To create interactive user interface in a web page
(e.g., menu, pop-up alert, windows, etc.)
▪ Manipulating web content dynamically
▪ Change the content and style of an element
▪ Replace images on a page without page reload
▪ Hide/Show contents
▪ Generate HTML contents on the fly
▪ Form validation
▪ AJAX (e.g. Google complete)
▪ etc.
SCRIPT TAG
Scripts in HTML must be inserted between <script> and
</script> tags.
Scripts can be put in the <body> and in the <head>
section of an HTML page.
The <script> Tag
To insert a JavaScript into an HTML page, use the
<script> tag.
The <script> and </script> tells where the JavaScript
starts and ends.
The lines between the <script> and </script> contain the
JavaScript:
EXTERNAL JAVASCRIPTS
Scripts can also be placed in external files. External
files often contain code to be used by several
different web pages.
External JavaScript files have the file extension .js.
To use an external script, point to the .js file in the
"src" attribute of the <script> tag:
A Simple JavaScript Example
<html>
<head><title>First JavaScript Page</title></head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
[Link]("<hr>");
[Link]("Hello World Wide Web");
[Link]("<hr>");
</script>
</body>
</html>
Embedding JavaScript
<html>
<head><title>First JavaScript Program</title></head>
<body>
<script type="text/javascript"
src="your_source_file.js"></script>
</body>
Inside your_source_file.js
</html>
[Link]("<hr>");
[Link]("Hello World Wide Web");
[Link]("<hr>");
▪ Use the src attribute to include JavaScript codes
from an external file.
▪ The included code is inserted in place.
Printing “Hello World”
Printing “Hello World”
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.
var answer = confirm("Are you sure?");
▪ Display a message in a dialog box with two buttons:
"OK" or "Cancel".
▪ confirm() returns true if the user click "OK".
Otherwise it returns false.
prompt()
prompt("What is your student id number?");
prompt("What is your name?”, "No name");
▪ Display a message and allow the user to enter a value
▪ The second argument is the "default value" to be
displayed in the input textfield.
▪ Without the default value, "undefined" is shown in the
input textfield.
▪ 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.
Printing “Hello World” Using Button - EVENT
MANIPULATING HTML ELEMENTS
To access an HTML element from JavaScript, you
can use the [Link](id) method.
Use the "id" attribute to identify the HTML element:
EXAMPLE
<body>
<h1>My First Web Page</h1>
<p id="demo">My First Paragraph</p>
<script>
[Link]("demo") .innerHTML="Hello”;
</script>
</body>
WRITING TO THE DOCUMENT OUTPUT
<h1>My First Web Page</h1>
<script>
[Link]("<p>My First JavaScript </p>");
</script>
JAVASCRIPT STATEMENTS
JavaScript statements are "commands" to the browser. The
purpose of the statements is to tell the browser what to do.
This JavaScript statement tells the browser to write "Hello
World" inside an HTML element with id="demo":
[Link]("demo").innerHTML="Hello World";
SEMICOLON ;
Semicolon separates JavaScript statements.
Normally you add a semicolon at the end of each
executable statement.
Using semicolons also makes it possible to write
many statements on one line.
JAVASCRIPT IS CASE SENSITIVE
JavaScript is case sensitive.
Watch your capitalization closely when you write
JavaScript statements:
A function getElementById is not the same as
getElementbyID.
A variable named myVariable is not the same as
MyVariable.
WHITE SPACE
JavaScript ignores extra spaces. You can add white
space to your script to make it more readable
var name="Hege";
var name = "Hege“;
BREAK UP A CODE LINE to break the statement
[Link]("Hello \
World!");
JAVASCRIPT COMMENTS
// Write to a heading:
[Link]("myH1").innerHTML="W
elcome to my Homepage";
/*
The code below will write
to a heading and to a paragraph,
and will represent the start of
my homepage:
*/
COMMENT CONT…
var x=5; // declare x and assign 5 to it
var y=x+2; // declare y and assign x+2 to it
JAVASCRIPT VARIABLES
Variable names must begin with a letter
Variable names can also begin with $ and _ (but we
will not use it)
Variable names are case sensitive (y and Y are
different variables)
JAVASCRIPT DATA TYPES
JavaScript variables can also hold other types of data,
like text values (name="John Doe").
In JavaScript a text like "John Doe" is called a string.
There are many types of JavaScript variables, but for
now, just think of numbers and strings.
When you assign a text value to a variable, put double or
single quotes around the value.
When you assign a numeric value to a variable, do not
put quotes around the value. If you put quotes around a
numeric value, it will be treated as text.
DATA TYPE EXAMPLES
var pi=3.14;
var name="John Doe";
var answer='Yes I am!';
DECLARING JAVASCRIPT VARIABLES
You declare JavaScript variables with the var
keyword
var carname;
carname = “Volvo”;
var carname = “volvo”;
JAVASCRIPT IS LOOSELY TYPED
JavaScript is weakly typed. This means that the
same variable can be used as different types:
Example
var x // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
Addition of two numbers in JS
Addition of two numbers – User Input
More examples – Factorial of a number
Addition of two numbers using function
if/else statement (same as C)
33
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
JS
CS380
for loop
34
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
} JS
var s1 = "hello";
var s2 = "";
for (var i = 0; i < [Link]; i++) {
s2 += [Link](i) + [Link](i);
}
// s2 stores "hheelllloo" JS
CS380
PROBLEM
[Link](cars[0] + "<br>");
[Link](cars[1] + "<br>");
[Link](cars[2] + "<br>");
[Link](cars[3] + "<br>");
[Link](cars[4] + "<br>");
[Link](cars[5] + "<br>");
[Link](cars[6] + "<br>");
[Link](cars[7] + "<br>");
[Link](cars[8] + "<br>");
[Link](cars[9] + "<br>");
[Link](cars[10] + "<br>");
SOLUTION
for (var i=0;i<=10;i++)
{
[Link](cars[i] + "<br>");
}
while loops
37
while (condition) {
statements;
} JS
do {
statements;
} while (condition);
JS
CS380
Popup boxes
38
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS
CS380
Array literals
◼ You don’t declare the types of variables in JavaScript
◼ JavaScript has array literals, written with brackets and
commas
Example: color = ["red", "yellow", "green", "blue"];
Arrays are zero-based: color[0] is "red"
◼ If you put two commas in a row, the array has an
“empty” element in that location
Example: color = ["red", , , "green", "blue"];
➢ color has 5 elements
However, a single comma at the end is ignored
➢ Example: color = ["red", , , "green", "blue”,]; still
has 5 elements
Four ways to create an array
◼ You can use an array literal:
var colors = ["red", "green", "blue"];
◼ You can use new Array() to create an empty array:
var colors = new Array();
You can add elements to the array later:
colors[0] = "red"; colors[1] = "blue"; colors[2]="green";
◼ You can use new Array(n) with a single numeric
argument to create an array of that size
var colors = new Array(3);
◼ You can use new Array(…) with two or more arguments
to create an array containing those values:
var colors = new Array("red","green", "blue");
The length of an array
◼ If myArray is an array, its length is given by
[Link]
◼ Array length can be changed by assignment beyond the
current length
Example: var myArray = new Array(5); myArray[10] = 3;
◼ Arrays are sparse, that is, space is only allocated for
elements that have been assigned a value
Example: myArray[50000] = 3; is perfectly OK
But indices must be between 0 and 232-1
Arrays
42
var name = []; // empty array
var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
JS
var a = ["Harry", "Dev", "Louis"];
var s = []; // [Link] is 0
s[0] = "Larry"; // [Link] is 1
s[1] = "Moe"; // [Link] is 2
s[4] = "Curly"; // [Link] is 5
s[4] = "Shemp"; // [Link] is 5
JS
CS380
Array functions
◼ If myArray is an array,
[Link]() sorts the array alphabetically
[Link]() reverses the array elements
[Link](…) adds any number of new
elements to the end of the array, and increases the
array’s length
[Link]() removes and returns the last
element of the array, and decrements the array’s
length
[Link]() returns a string containing the
values of the array elements, separated by commas
Array methods
44
var a = ["Stef", "Jason"]; // Stef, Jason
[Link]("Brian"); // Stef, Jason, Brian
[Link]("Kelly"); // Kelly, Stef, Jason, Brian
[Link](); // Kelly, Stef, Jason
[Link](); // Stef, Jason
[Link](); // Jason, Stef
JS
array serves as many data structures: list, queue,
stack, ...
methods: concat, join, pop, push, reverse, shift,
slice, sort, splice, toString, unshift
push and pop add / remove from back
unshift and shift add / remove from front
shift and pop return the element that is removed
Arrays
◼ As in C and Java, there are no “true”
multidimensional arrays
However, an array can contain arrays
The syntax for array reference is as in C and Java
◼ Example:
var a = [ ["red", 255], ["green", 128] ];
var b = a[1][0]; // b is now "green"
var c = a[1]; // c is now ["green", 128]
var d = c[1]; // d is now 128
String type
46
var s = "Connie Client";
var fName = [Link](0, [Link](" ")); // "Connie"
var len = [Link]; // 13
var s2 = 'Melvin Merchant';
JS
methods: charAt, charCodeAt, fromCharCode,
indexOf, lastIndexOf, replace, split,
substring, toLowerCase, toUpperCase
charAt returns a one-letter String (there is no char type)
length property
Strings can be specified with "" or ''
concatenation with + :
1 + 1 is 2, but "1" + 1 is "11"
ADDING STRINGS AND NUMBERS
x=5+5;
y="5"+5;
z="Hello"+5;
output
10
55
Hello5
Splitting strings: split and join
48
var s = "the quick brown fox";
var a = [Link](" "); // ["the", "quick", "brown", "fox"]
[Link](); // ["fox", "brown", "quick", "the"]
s = [Link]("!"); // "fox!brown!quick!the"
JS
split breaks apart a string into an array using a
delimiter
can also be used with regular expressions (seen later)
join merges an array into a single string, placing a
delimiter between them
Three ways to create an object
◼ You can use an object literal:
var course = { number: “CS450", teacher="Dr. ABC" }
◼ You can use new to create a “blank” object, and add fields
to it later:
var course = new Object();
[Link] = “CS450";
[Link] = "Dr. ABC";
◼ You can write and use a constructor:
function Course(n, t) { // best placed in <head>
[Link] = n;
[Link] = t;
}
var course = new Course(“CS450", "Dr. ABC");
A REAL LIFE OBJECT. A CAR:
PROPERTIES AND METHODS
Properties are values associated with an object.
Methods are actions that can be performed on
objects.
Events
◼ Most browser DOM objects have “events”
associated with them
Recall Javascript objects include windows, frames,
forms, form fields, links, etc.
◼ An event is Javascript code that can be
triggered when something happens to a
Javascript object
Example: clicking on a hyperlink
Example: leaving a form field
Events
◼ Some events will behave differently depending
on whether the code associated with the event
returns a true or a false value
◼ Example: If the form onsubmit event returns
false, the form is not submitted
◼ All events start with “on”, ex: onclick,
onsubmit, etc. This makes them easy to
distinguish
Onclick Event
56 CS380
Onmouseover and Onmouseout Event
57 CS380
Onsubmit Event
58 CS380
Onfocus Event
59 CS380
Onchange Event
60 CS380
Onblur Event
61 CS380
Onload Event
62 CS380
JavaScript - Errors
& Exceptions
Handling
JAVA SCRIPT ERROR HANDLING
The try statement lets you to test a block of code
for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
JAVASCRIPT TRY AND CATCH
The try statement allows you to define a block of
code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of
code to be executed, if an error occurs in the try
block.
The JavaScript statements try and catch come in
pairs.
JAVASCRIPT THROWS ERRORS
When an error occurs, when something goes
wrong, the JavaScript engine will normally stop,
and generate an error message.
The technical term for this is: JavaScript will throw
an error.
SYNTAX
try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}
Try and catch
71 CS380
Try and catch
72 CS380
<html>
<head>
<script type = "text/javascript"> function
myFunc() {
var a = 100; var b = 0;
try {
if ( b == 0 ) {
throw( "Divide by zero error." );
} else {
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" />
</form>
</body>
</html>
EXAMPLE
<script>
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page";
alert(txt);
}
}
</script>
<input type="button" value="View message" >
Try catch and finally
75 CS380
JAVASCRIPT FORM VALIDATION
JavaScript can be used to validate data in HTML forms
before sending off the content to a server.
Form data that typically are checked by a JavaScript
could 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?
77 CS380
NULL FIELDS
function validateForm()
{
var x=[Link]["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
E-MAIL VALIDATION
function validateForm()
{
var x=[Link]["myForm"]["email"].value;
var atpos=[Link]("@");
var dotpos=[Link](".");
if (atpos<1 || dotpos<atpos+2 ||
dotpos+2>=[Link])
{
alert("Not a valid e-mail address");
return false;
}
}