Intro to JavaScript
Supplemental Material:
http://www.w3schools.com/js/
http://www.learn-javascript-tutorial.com/
What is JavaScript?




JavaScript is a scripting language
for the Web
Performed on the client (browser) machine
JavaScript was developed in 1995 by
Brendan Eich for the then Netscape
Navigator 2.0 browser
JavaScript has evolved over years and is
supported in all the modern browsers
JavaScript



Java
Java and JavaScript share many
characteristics, i.e. both are object-oriented
languages
but…
Java is a compiled language and it has a
number of capabilities, instructions, and
libraries not available to JavaScript
JavaScript is an interpreted language
that can run on any OS platform
Disadvantages of
JavaScript

Because executes on client, it
can be used for malicious purposes



Why some users may disable JavaScript
Inability to hide source code poses a
lack of protection of intellectual property
JavaScript may be implemented
differently with different browsers

Be sure to test with all major browsers
Advantages of
JavaScript




JavaScript code executes faster
without round trip to the server
Simple to learn and implement
Versatile in that it works well with
other programming languages
Results in lower demand on the Web
server and application server
Relationship to HTML & CSS

JavaScript
plays a key
role in
Dynamic
HTML




JavaScript
CSS
HTML
DOM
Class Goals for JavaScript

After this brief introduction you should
be able to:




Describe the syntax of JavaScript
Understand the best uses of JavaScript
Know how to insert a JavaScript program
into an XHTML file
Make use of existing JavaScript code
in your Web site
Client-Side Scripting




JavaScript is a
scripting language
The JavaScript
engine runs on
the client machine
in the browser
Work is done on
the client, not the
server
Takes some of the
processing burden
off the server
Document Object Model



Known as the DOM
This is the internal representation
of an HTML web page
As a page loads, the DOM is stored
in the browser’s memory
 HTML elements are element nodes
 Text is stored in text nodes
 Also has attribute and comment nodes
HTML DOM


The HTML is represented in a DOM tree structure
These nodes can be modified by JavaScript
http://www.w3schools.com/htmldom/default.asp
The DOM Event Cycle



DOM scripting allows you to use JavaScript to update a web
page in response to user actions
When the DOM is modified, the web browser updates the page
When the event handler is finished, the web browser waits for
another event
Changing HTML Elements



To insert JavaScript
into an HTML page
use the <script>
tag
The <script> and
</script> tell where
JavaScript begins
and ends
Lines between are
executed by the
browser
JavaScript Example
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo"></p>
<script type="text/javascript">
document.getElementById("demo").
innerHTML=Date();
</script>
</body>
</html>
Where to Insert JavaScript?

There are several places where these
scripts may be inserted:

In the <head> area of the page



Header scripts cannot generate output in HTML
document but can be referred to by other scripts
Header scripts are often used for functions
In the <body> area of the page

Output from body scripts are displayed as part of
the HTML document when the browser loads the
page
Where to Insert JavaScript? (cont.)

After the </body>



Scripts here can see/use all the XHTML tags
in the body
An example use: place a cursor in a textbox
Within an XHTML tag, such as <body>,
<a>, <input>, <img> or <form>


This is called an event handler and allows the
script to work with HTML elements.
In this case, no <script> tag is used.
Using an External JavaScript





JavaScript like CSS can also be placed in
external files
External JavaScript files often contain code
used on several pages
JavaScript in the file runs as if it were coded
in a script element
These files have an extension of .js
<script type="text/javascript“ src="xxx.js">
</script>
External file has no <script></script> tag
JavaScript Code




JavaScript code is a step by step
sequence of statements
Each statement is executed by the
browser in the sequence it appears
You may have more than one script
element in a web page
White space is usually ignored
JavaScript Statements


JavaScript is case sensitive so be careful
with your spelling and capitalization
A JavaScript statement is a command
to the browser


document.write(“Hello World”);
While the semicolon (;) is optional,
semicolons make it possible to have
more than one statement on a line
JavaScript Syntax - Blocks



JavaScript statements can be grouped
together into blocks
A block begins with a left curly brace {
and ends with a right curly brace }
Some often used blocks include:



Functions
Loops
If Blocks
JavaScript Syntax - Comments

Three kinds of JavaScript comments



Block comments allow multi-line comment
/* this is an example of a block comment that
may span more than one line */
End of line comments
// from the slash to the end of line is a comment
Comments for older browsers to ignore JavaScript.
Needs no closing like HTML comments do.
<! -- <script type=“text/JavaScript”>
// </script> - - >
JavaScript Variables


As with most programming languages,
variables are containers for storing
information
Use the var keyword to declare variables



var x;
var firstname;
Rules for variable names include:


Variable names are case sensitive
Variable names must begin with a letter or the
underscore character
Local JavaScript Variables

If declared inside a function, a variable
becomes local



It can only be accessed within that function
 Local variables are said to have local scope


var x=5;
var carname=“Volvo”;
Can have local variables in different functions with
the same name
Local variables are destroyed when the
function exits
Global JavaScript Variables



Variables declared outside a function become
global variables
All scripts and functions on the page can
access these variables
If you declare a variable without the “var”,
the variable always becomes global



x=5;
Carname=“Volvo”;
Global variables are destroyed when you
close the page
Arrays – How to use them



An array is a variable that can hold more than
one value at a time
Values have an index, beginning with 0
Modify values by using the index


myCars[0]="Opel";
Write value from an array element

document.write(myCars[0]);
Creating an Array – 3 Methods

1. Create an
empty array, then
fill it with values

2. Create a condensed array
var myCars =
new Array("Saab","Volvo","BMW");
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

3. Create a literal array
var myCars=
["Saab","Volvo","BMW"];
JavaScript Operators


As with any programming language,
JavaScript uses a set of operators to process
information.
These include:






Arithmetic operators
Bitwise operator
Assignment operators
Comparison operators
Logical operators
String operators
Arithmetic and Assignment
Operators







+
Addition operator
Example: A + B
–
Subtraction operator:
Example: A – B
*
Multiplication operator:
Example: A * B
/
Division operator:
Example: A/B
++ Increment operator:
Example: A++
-Decrement operator:
Example: A-% Modulus operator:
Example: A % B


The equal sign, ‘=‘, sets the
left element equal to the
value of the right element
Other short cuts:











a
a
a
a
a
a
a
a
a
a
a
+= b
-= b
*= b
/= b
%= b
&= b
|= b
^= b
<<= b
>>= b
>>>= b
Comparison and Logical
Operators





>
Returns true if the
first value is greater
than the second
>= Returns true if the
first value is greater
than or equal to the
second
<
Returns true the first
value is less than
the second
<= Returns true if the first
value is less than
or equal to the second
== Returns true if first
value is equal to second

===

!=

!

&&

||
Exactly equal to
(value and type)
Returns true if first
value is not equal to
second
Returns true if its
operand is zero or
false
Returns false if
either operand is
zero or false
Returns false if both
operands are zero
or false
Strings and Escape Characters



Strings are identified
using double quotes,
e.g., "This is a
JavaScript string.“
Two strings can be
concatenated using
the ‘+’, e.g., “Tom "
+ “Smith" equals
“Tom Smith"
Some characters are
interpreted as white
space







Some characters are
escape characters
and require an
alternative method
of being entered.
\n newline
\t tab
\r carriage return
\\ backslash
\" double quote
\' single quote
Conditional Statements




Conditional statements are used to perform
different actions for different decisions
if statement – use this to execute some
code if a condition is true
if..else statement - use to execute code if
the condition is true and another code if the
condition is false
if..else..if..else statement – use to select
one of many blocks of code to be executed
if and if..else Statements
if Example
<script
type="text/javascript">
//Write a "Good morning"
greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();
if (time<10) {
document.write
("Good morning");
}
</script>
If..else Example
<script type="text/javascript">
//If the time is <10, get a "Good morning"
//Otherwise you will get a "Good day" greeting.
var d = new Date();
var time = d.getHours();
if (time < 10){
document.write("Good morning!");
}
else {
document.write("Good day!");
}
</script>
If..else..if..else Statement
If..else..if..else Example
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10) {
document.write("<b>Good morning</b>");
}
else if (time>=10 && time<16) {
document.write("<b>Good day</b>");
}
else {
document.write("<b>Hello World!</b>");
}
</script>
JavaScript Pop Up Boxes




Java Script has 3 types of pop up boxes:
Alert, Confirm and Prompt
An alert box – used to make sure
information comes to the user,
user has to click “OK”
A confirm box is used to get the user to
verify or accept something,
user has to click “OK” or “Cancel”
A prompt box is often used if you want the
user to input a value before entering a page.
Functions in JavaScript


A function is a block of code that will be
executed by an event or call to the function
There are three important things
you need to include with a function:




the function's name
any parameters passed to the function
the code to execute
The usual format is shown below:
function functionName(parameters)
{
// statements to be executed
}
The return Statement


The return statement
is used to specify a
value to be returned
from the function
Functions that are
going to return a
value must have a
return statement
<html>
<head>
<script type="text/javascript">
function product(a,b)
{ return a*b; }
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>
</html>
JavaScript Methods








Date Methods - set variables to the clock time
Window Methods - open and close new windows
Document Methods - generate new documents
Form Methods - select form items, send the cursor
to text boxes and submit forms.
History Methods - press the reader’s 'Back' button
and other tricks.
Text Methods - define the look of text variables
Math Methods - sin, cos, round, random, etc.
MessageBox Methods - Alert, Prompt, and Confirm
Date Methods

now = new Date () in its raw form
is both the date and time


now.toLocaleString( ) converts raw
date/time to the local convention


Sun Oct 30 2011 17:42:02 GMT -0600
(Mountain Daylight Time)
Sunday, October 30, 2011 5:58:58 PM
Other Date Methods:


now.getDate(), now.getMonth(), now.getYear()
now.getHours(), now.getMinutes(),now.getSeconds()
window.open() Method


MyWindow= window.open();
Has 3 optional parameters:




A URL so the window contains a specific HTML
document.
A title for the window.
A set of options for the window’s appearance, i.e.
height and width.
Example:
NewWindow.window.open(“mytest.htm”);
Window.open( ) Options
Option
choice
description
toolbar
yes/no or 1/0
Display toolbar
status
yes/no or 1/0
Display status bar at bottom
of window
menubar
yes/no or 1/0
Display menubar
scrollbars
yes/no or 1/0
Display horizontal and vertical
scrollbars
resizable
yes/no or 1/0
Window can be resized
location
yes/no or 1/0
Display location of box
directories
yes/no or 1/0
Display directory of buttons
width
# of pixels
Exact width of new window
height
3 of pixels
Exact height of new window
Example Window Options
//Create new Window
options = "toolbar=0,status=0,menubar=0,scrollbars=0," +
"resizable=0,width=300,height=200";
newwindow=window.open("","mywindow", options);
newwindow.document.writeln(LocalTime);
newwindow.document.write(contents);
newwindow.document.close();
JavaScript on Web Pages
There are two ways JavaScript is
executed in web pages


As the page is loaded, embedded scripts
are executed and the script's output is
inserted where the script occurred in the
page
If an event occurs that is associated
with a script, the script is executed
Events



Every object on a page has ‘Events’ which
can trigger JavaScript functions.
For example, the ‘onClick’ event of a form
button can determine the function to execute
when a button is clicked.
Images cannot have events,
but links can.

You can add an event to an image by creating a
link with nothing in it around the image.
Some JavaScript Events
Event
Applies to
Occurs when
Event
Handler
abort
images
User aborts image load by clicking
a button or link
onAbort
blur
windows, frames, and
all form elements
User removes input focus from
window, frame, or form element
onBlur
click
buttons, links
User clicks form element or link
onClick
change
text fields, select lists
User changes value of element
onChange
error
images , windows
Loading of document or image
causes an error
onError
focus
windows, frames, and
all form elements
User gives input focus to window,
frame or form element
onFocus
load
document body
User loads the page
onLoad
Some JavaScript Events cont.
Event
Applies to
Occurs when
Event
Handler
mouseout
areas, links
User moves a mouse out of an
area or link
onMouseout
mouseover
links
User moves mouse over a link
onMouseOver
reset
forms
User resets a form (Reset Button)
onReset
select
text fields, textareas
User selects form element’s input
field
onSelect
submit
submit button
User submits a form
onSubmit
unload
document body
User exits the page
onUnload
onLoad Events



This event is placed in the <body> tag
It is used to trigger events automatically
upon loading the page
Possible uses include:




use to display welcome message
place focus in an element
execute a special effect
prompt for a password
getElementById( ) Method


This is a method of the
document object and
can only be accessed
through the document
Give your HTML
elements an id attribute
so they can be accessed
in the JavaScript
getElementById Example
<script type= "text/javascript">
function notEmpty(){
var myTextField =
document.getElementById('myText');
if(myTextField.value != "") alert("You entered: "
+ myTextField.value)
else alert("Would you please enter some text?")
}
</script>
<input type=“text” id=“myText” />
<input type=“button” onclick=“notEmpty()”
value=“Form Checker” />
innerHTML Property

Each HTML element has an innerHTML property that
defines the text between the opening and closing tags


<h1>The innerHTML Text</h1>
If you want to access the text of a non-input HTML
element, make use of this innerHTML property
innerHTML Example
<script type="text/javascript">
function changeText(){
document.getElementById('boldStuff').innerHTML= 'Fred Flinstone';
}
</script>
<p>Welcome to the site <span id=“boldStuff”>dude</span> </p>
<input type='button' onclick=“changeText()” value=“Change Text”/>
Finding JavaScript Code




There are many web sites that provide
JavaScript code you can easily add to your
Web site
You can use tested JavaScript code in your
web pages even though you didn’t write it
and may not fully understand it
Most sites provide instructions for
using the code
Search for terms like “free Javascript code”
or “Javascript code examples”
Example
JavaScript
Code Site
http://javascript.internet.
com/alphabetical-listing/
Interesting Uses of JavaScript

JavaScript Image Rollovers


JavaScript Image Swaps


An image swap occurs when an onClick event handler replaces
one image with another image
JavaScript Slideshows


An image rollover occurs when a onMouseOver event over one
image causes that image to be temporarily replaced by another
image
Uses JavaScript to provide controls to show a slideshow of image
and titles
JavaScript for Form Validation – Coming soon!


Provides data validation before form data is sent for processing
We will cover this in depth later in the semester
JavaScript Summary


JavaScript is a client-side scripting language
run in the Web browser
The DOM is a collection of nodes that
represent the current page


DOM scripting allows the changing of the DOM
by using JavaScript
There are many interesting JavaScript
applications whose code is freely available

The challenge- You have to figure out
how to use these
Get Started
with
JavaScript!
Descargar

An Introduction to HTML