JavaScript
Prof.N.Nalini
AP(Sr)
SCOPE
VIT
Introduction
A scripting languages are a form of
programming language that are "embedded" in
Web pages and interpreted at run time.
Executed by an interpreter contained within the
web browser (scripting host)
Interpreter uses a scripting engine
Converts code to executable format each time it runs
Converted when browser loads web document
Scripting Language
Two formats:
Client-side
Program runs on client
(browser)
Server-side
Program runs on server
JavaScript’s role on the Web
HTML
Purpose tell the browser how a document should appear
Static can view or print (no interaction)
JavaScript
Purpose make web pages (documents) more dynamic and
interactive
Change contents of document, provide forms and
controls, animation, control web browser window, etc.
The JavaScript
JavaScript: the first Web scripting language,
developed by Netscape in 1995
syntactic similarities to Java/C++, but simpler & more flexible
(loose typing, dynamic variables, simple objects)
JScript: Microsoft version of JavaScript, introduced in
1996
same core language, but some browser-specific differences
fortunately, IE & Netscape can (mostly) handle both
JavaScript & JScript
What can we do with JavaScript?
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.
Advantages of JavaScript
Speed. Being client-side, JavaScript is very fast because
any code functions can be run immediately instead of
having to contact the server and wait for an answer.
Simplicity. JavaScript is relatively simple to learn and
implement.
Versatility. JavaScript plays nicely with other languages
and can be used in a huge variety of applications.
JavaScript can be inserted into any web page regardless
of the file extension. JavaScript can also be used inside
scripts written in other languages such as Perl and PHP.
Server Load. Being client-side reduces the demand on
the website server.
Useful Resources and Interesting
Examples
JavaScript Tutorials
http://www.w3schools.com/
Some examples from W3Schools
JavaScript Examples
JavaScript Object Examples
JavaScript HTML DOM Examples
JavaScript DHTML GUI Components
http://www.java2s.com/Code/JavaScript/GUI-
Components/CatalogGUI-Components.htm
EditGrid
http://www.editgrid.com/
A Simple Script
<html>
<head><title>First JavaScript Page</title></head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<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>
</html> Inside your_source_file.js
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
Use the src attribute to include JavaScript codes
from an external file.
The included code is inserted in place.
Hiding JavaScript from Incompatible
Browsers
<script type="text/javascript">
<!–
document.writeln("Hello, WWW");
// -->
</script>
<noscript>
Your browser does not support JavaScript.
</noscript>
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.
Variable on-the-fly
<head>
<script language=“JavaScript”>
Variable declaration
var id;
id = prompt(“What is your student id number?”);
alert(id);
name = prompt(“What is your name?”,”No name”);
alert(name);
</script>
</head>
We should use “var” because it is more
easy to keep track of the variables. 16
Identifier
Same as Java/C++ except that it allows an
additional character – '$'.
Contains only 'A' – 'Z', 'a' – 'z', '0' – '9', '_', '$'
First character cannot be a digit
Case-sensitive
Cannot be reserved words or keywords
Variable and Variable Declaration
<head><script type="text/javascript">
// We are in the default scope – the "window" object.
x = 3; // same as "window.x = 3"
var y = 4; // same as "y = 4" or "window.y = 4"
{ // Introduce a block to creat a local scope
x = 0; // Same as "window.x = 0"
var y = 1; // This is a local variable y
}
alert("x=" + x + ", y=" + y); // Print x=0, y=4
</script></head>
Local variable is declared using the keyword 'var'.
Dynamic binding – a variable can hold any type of value
If a variable is used without being declared, the variable is created
automatically.
If you misspell a variable name, program will still run (but works incorrectly)
Data Types
Primitive data types
Number: integer & floating-point numbers
Boolean: true or false
String: a sequence of alphanumeric characters
Composite data types (or Complex data types or reference
data types )
Object: a named collection of data
Array: a sequence of values (an array is actually a predefined
object)
Special data types
Null: the only value is "null" – to represent nothing.
Undefined: the only value is "undefined" – to represent the value of
an unintialized variable
Numeric Data Types
It is an important part of any programming
language for doing arithmetic calculations.
JavaScript supports:
Integers: A positive or negative number with no
decimal places.
Ranged from –253 to 253
Floating-point numbers: usually written in exponential
notation.
3.1415…, 2.0e11
20
Integer and Floating-point number
example
<script language=“JavaScript”>
var i = 100;
var f = 3.0e10;
// floating-point number 30000000000
document.write(i);
document.write(f);
</script>
The integer 100 and the number
30,000,000,000 will be appeared in the
browser window.
21
Boolean Values
A Boolean value is a logical value of either true
or false. (yes/no, on/off)
Often used in decision making and data
comparison.
In JavaScript, you can use the words “true” and
“false” directly to indicate Boolean values.
22
Boolean value example
<head>
<script language=“JavaScript”>
var result;
result = (true*10 + false*7);
alert(“true*10 + false*7 = “, result);
</script>
</head>
The expression is converted to
(1*10 + 0*7) = 10
They are automatically converted. 23
Strings
A string variable can store a sequence of
alphanumeric characters, spaces and special
characters.
String can also be enclosed in single quotation
marks (‘) or in double quotation marks (“).
What is the data type of “100”?
String but not number type
Use escaped character sequence to represent
special character (e.g.: \", \n, \t)
24
Strings example
<head>
<script language=“JavaScript”>
document.write(“This is a string.”);
document.write(“This string contains ‘quote’.”);
var myString = “My testing string”;
alert(myString);
</script>
</head>
Unlike Java and C, JavaScript does not
have a single character (char) data type.
25
typeof operator
<head>
<script language=“JavaScript”>
var x = “hello”, y;
alert(“Variable x value is “ + typeof(x));
alert(“Variable y value is “ + typeof(y));
alert(“Variable x value is “ + typeof(z));
</script>
</head>
An unary operator that tells the type of its
operand.
Returns a string which can be "number", "string",
"boolean", "object", "function", "undefined", and
"null" 26
Null & Undefined
An undefined value is represented by the
keyword "undefined".
It represents the value of an uninitialized variable
The keyword "null" is used to represent
“nothing”
Declare and define a variable as “null” if you want the
variable to hold nothing.
Avoid leaving a variable undefined.
Null & Undefined example
<html>
<head>
<title> Null and Undefined example </title>
<script language=“JavaScript”>
var test1, test2 = null;
alert(“No value assigned to the variable” + test1);
alert(“A null value was assigned” + test2);
</script>
</head>
<body> … </body>
</html>
28
Type Conversion (To Boolean)
The following values are treated as false
null
undefined
+0, -0, NaN (numbers)
"" (empty string)
Type Conversion
Converting a value to a number
var numberVar = someVariable – 0;
Converting a value to a string
var stringVar = someVariable + "";
Converting a value to a boolean
var boolVar = !!someVariable;
== vs ===
// Type conversion is performed before comparison
var v1 = ("5" == 5); // true
// No implicit type conversion.
// True if only if both types and values are equal
var v2 = ("5" === 5); // false
var v3 = (5 === 5.0); // true
var v4 = (true == 1); // true (true is converted to 1)
var v5 = (true == 2); // false (true is converted to 1)
var v6 = (true == "1") // true
document.getElementById
Used to change anything in your document (web
page) that has an id
Then you can change different aspects of the
element with that id:
<img src = “zombie.jpg” height = “500” width = “300”
alt = “eat your brain” id = “img1”>
You can use document.getElementById to change
the:
src
height
width
alt
getElementById()
<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" />
</head>
<body style = "background-color:#000000; color: red;">
<h1> Hello</h1>
<p> <img src = "ball.jpg" width = "100" height = "100"
alt = "a ball picture" id = "ball1"></p>
<script>
var x = prompt("What size should the ball's width be?")
document.getElementById("ball1").width = x
</script>
</body>
</html>
We can use getElementById to change
CSS style:
<!DOCTYPE html><html><head> <meta charset= "utf-8" /></head>
<body>
<p id = "firstp"> This is a paragraph</p>
<p id = "secondp">This is a second paragraph</p>
<script>
document.getElementById("firstp").style.color = "#9999FF";
document.getElementById("firstp").style.fontSize = "120%";
document.getElementById("firstp").style.backgroundColor="#332277";
document.getElementById("firstp").style.textAlign = "right";
document.getElementById("firstp").style.padding = "30px";
document.getElementById("firstp").style.borderWidth = "8px";
document.getElementById("firstp").style.borderColor = "green";
document.getElementById("firstp").style.borderStyle = "inset";
</script>
</body></html>
innerHTML
The innerHTML is what is between the opening and the closing
tag, regardless of what the tag is:
<p id = “firstp”> This is the innerHTML text because it goes between the
opening and closing tag
</p>
Above, the innerHTML is: “This is the innerHTML text because it goes
between the opening and closing tag”
To change it:
document.getElementById(“firstp”).innerHTML = “new text for
paragraph”
<h1 id = “firsth”>Title goes here </h1>
Above: innerHTML is: Title goes here
To change:
document.getElementById(“firsth”).innerHTML = “New Title”
innerHTML (cont.)
<p id = “linked”> <a href = “xx.com” id = “firstlink”> link to udel </a>
</p>
What is the innerHTML of linked?
What is the innerHTML of firstlink?
How would you change the innerHTML of linked to a new link?
<ol id = “list1”>
<li id = “firstItem”> cats </li>
<li id=“seconditem”> dogs </li>
</ol>
What is the innerHTML of list1?
What is the innerHTML of firstitem?
How would you change the innerHTML of list1 to a new list?