CS 312
Internet Concepts
Web Programming:
JavaScript
Dr. Michele Weigle
Department of Computer Science
Old Dominion University
mweigle@cs.odu.edu
1
Outline
◆ What is JavaScript?
◆ JavaScript Syntax
◆ JavaScript and HTML DOM
◆ Event Handlers
◆ Pop-Ups and Functions
◆ Form Validation
◆ More Examples
2
JavaScript
◆ A scripting language designed to add interactivity
to HTML page
» lightweight programming language
◆ Usually embedded directly into HTML pages
◆ Interpreted language
» needs no preliminary compilation
◆ Similar in syntax to Java, but not Java
3
JavaScript Capabilities
◆ Gives HTML designers a programming tool
◆ Can be used to
» Put dynamic text into an HTML page
» React to events
❖ex: open new windows, changing images as mouse moves
over
» Read and write HTML elements
» Validate entered data
» Detect the visitor’s browser
» Create cookies
4
Client-Side JavaScript
◆ Interpreted by the browser upon running
» Displaying the page as read and executing JavaScript
statements
◆ Can respond to user events
◆ Generally embedded in HTML file
◆ Can also be specified in separate file (with
extension .js)
5
History / Purpose
History :
1990s: developed at Netscape (orig. LiveScript)
1997: ECMAScript standardized
1998: ISO standard
Purpose: Add client-side interaction/behavior
PHP: server-side
JavaScript: client-side
client executing connected by server executing
JavaScript Ajax PHP
6
Outline
◆ What is JavaScript?
◆ JavaScript Syntax
◆ JavaScript and HTML DOM
◆ Event Handlers
◆ Pop-Ups and Functions
◆ Form Validation
◆ More Examples
7
JavaScript Comments
◆ Comments in HTML
<!-- This is a comment -->
◆ Comments in JavaScript
» Single line
// This is a comment
» Multiple lines
/* Starting comment
Ending comment */
8
Including JavaScript
◆ JavaScript inside HTML:
<script>
JavaScript code
</script>
◆ JavaScript in a separate file, use:
<script src="scriptName.js"> </script>
Note: You may see type="text/javascript" inside the
<script> tag in older examples, but it's no longer necessary for
JavaScript
9
Programming Elements
◆ Declare a variable
» var variableName = value;
◆ Conditional
» if (condition) {statements;} else
{statements;}
◆ Loops
» while (condition) {statements;}
» do {statements;} while (condition)
» for (initial value; condition; update)
{statements;}
◆ Functions
» function functionName
(var1,var2,...,varX) {statements;} 10
Arrays and Objects
Arrays - standard arrays with numbered indexes
var arr1 = [1, 7, 10, 15];
document.write(arr1[3]); 15
document.write(arr1.length); 4
arr1.push(20);
document.write(arr1); 1, 7, 10, 15,
20
Objects - special type with named indexes (like associative arrays in
other languages)
var notArray = [];
notArray.flavor = 'vanilla';
notArray.size = 'giant';
document.write(notArray.flavor); vanilla
Refs: https://www.w3schools.com/js/js_arrays.asp,
https://www.w3schools.com/js/js_object_definition.asp, https://www.w3schools.com/js/js_object_display.asp 11
Outline
◆ What is JavaScript?
◆ JavaScript Syntax
◆ JavaScript and HTML DOM
◆ Event Handlers
◆ Pop-Ups and Functions
◆ Form Validation
◆ More Examples
12
JavaScript and HTML DOM
◆ When a webpage is loaded, the browser creates a
Document Object Model of the page.
◆ The HTML DOM model is constructed as a tree
of Objects:
Ref: https://www.w3schools.com/js/js_htmldom.asp
13
JavaScript and HTML DOM
◆ Each node has
» attributes, methods
» all HTML attributes are accessible
» content is accessible
content tag
empty tag
<p id="p1"> </p>
document.getElementById('p1').innerHTML =
<p id="p1">Hello!
"Hello!"
</p>
<input type="text" id="name"
for JavaScript name="name" />
for PHP
document.getElementById('name').value =
Hello!
"Hello!"; 14
Useful Document Methods
◆ write ("string")
» write to the document as it's loading
◆ writeln ("string")
» write to the document as it’s loading and insert a
newline character at the end (remember that newlines
don't do much by themselves in HTML)
◆ getElementById("string")
» access any element on the page via its id attribute
» can alter the element using .innerHTML
Refs: https://www.w3schools.com/js/js_htmldom_document.asp
https://developer.mozilla.org/en/DOM/document 15
Useful Document Properties
◆ URL
» returns URL of the current document
◆ lastModified
» returns date and time document was last modified
◆ links[]
» an array containing all of the links on the page
◆ referrer
» string that specifies the URL of the page that contained
the link to the current page
Ref: https://developer.mozilla.org/en/DOM/document
16
JavaScript Example
Display a Message – Script in <head> <!DOCTYPE>, <html>
tags omitted to save space
<head>
<title>document.write Example 1</title>
<script>
document.write ("This is a message written when the page starts to
load.");
</script>
</head>
body element sent in HTTP response:
displayed with 'view-source'
displayed page:
<body>
<h1>document.write Example 1</h1> modified source (after JavaScript executed by
browser):
displayed in Inspector
<p>This is an example of including JavaScript in the HTML header.</p>
</body>
http://www.cs.odu.edu/~mweigle/cs312/examples/js/write-head.html
17
JavaScript Example
Display a Message - Script in <body>
<head>
<title>document.write Example 2</title>
</head>
<body>
<h1>document.write Example 2</h1>
<script>
document.write ("This is a message written when the page starts to
load.");
</script>
<p>This is an example of including JavaScript in the HTML body.</p>
http://www.cs.odu.edu/~mweigle/cs312/examples/js/write-body.html
18
JavaScript Example
Display a Message – using getElementById
<head>
Named element has
<title>getElementById Example</title>
to appear before
</head>
getElementById
<body>
<h1>getElementById Example</h1>
<p>This is an example of using getElementById to add text.</p>
<div id="target"></div>
<script>
document.getElementById("target").innerHTML = "<em>This text is
written by the script.</em>";
</script>
http://www.cs.odu.edu/~mweigle/cs312/examples/js/getelementbyid.html 19
Outline
◆ What is JavaScript?
◆ JavaScript Syntax
◆ JavaScript and HTML DOM
◆ Event Handlers
◆ Pop-Ups and Functions
◆ Form Validation
◆ More Examples
20
JavaScript Event Handlers
Allows a JavaScript function to be executed when the user does
something
◆ onclick - when the mouse clicks an object
◆ onload - when the page or image is finished loading
◆ onmouseover - when the mouse is moved over an element
◆ onmouseout - mouse exits
◆ onmousedown - mouse pressed
◆ onchange - form element changes
◆ onsubmit - form submitted
<input type="submit" onMouseOver="this.color='red'"
onMouseOut="this.color='gray'" />
<input type="submit" onclick="validate_form()">
Ref: http://www.w3schools.com/jsref/dom_obj_event.asp
21
Outline
◆ What is JavaScript?
◆ JavaScript Syntax
◆ JavaScript and HTML DOM
◆ Event Handlers
◆ Pop-Ups and Functions
◆ Form Validation
◆ More Examples
22
Alerts
◆ Alerts are pop-up boxes with buttons
» alert("sometext");
❖Pops up a box that says sometext
◆ Confirm
» confirm("sometext");
❖Pops up a box that says sometext with OK (returns true) and
Cancel (returns false) buttons
◆ Prompt
» prompt("sometext","defaultvalue");
❖Pops up a box with a text box that asks for user input
❖If the user clicks "OK" the box returns the input value
❖If the user clicks "Cancel" the box returns null.
https://www.w3schools.com/js/js_popup.asp
23
Example Function with Alert
<h1>Alert Example (with a Function)</h1>
<script>
function displaymessage()
{ function definition
alert("Hello World!");
}
</script>
<p>Press the button to display the message.</p>
<input type="button" value="Click Here"
onclick="displaymessage()" />
function call
http://www.cs.odu.edu/~mweigle/cs312/examples/js/alert.html
24
Example Alert on Click, Using External File
<head>
<script src="externalFunction.js">
</script>
</head>
<body>
<p onclick="start()" style="border: 2px solid red;">
If you click on this paragraph, then it will call an external
script function named "start" in the file named
"externalFunction.js". Click anywhere in this paragraph and you’ll
get an alert.</p>
<p>Another paragraph, click and no alert.</p>
</body>
externalFunction.js: externalFunction.js must be
function start() in the same directory as the HTML
{ file that uses it, or the directory must
alert ("Hello, glad you be specified in the HTML file (src
clicked!"); attribute).
}
http://www.cs.odu.edu/~mweigle/cs312/examples/js/click.html
25
Example Function with Prompt
<head>
<title>Prompt Example</title>
<script>
function display_prompt()
{
var name = prompt("Please enter your name","Harry
Potter");
return name;
}
</script>
</head>
<body>
http://www.cs.odu.edu/~mweigle/cs312/examples/js/prompt.html
26
Example Passing Arguments
<script>
function userAlert (label)
{
alert (label);
}
</script>
<form>
<label>Enter alert text: <input type="text" id="alertText"/>
</label>
<br />
<input type="button" value="Submit"
onclick="userAlert(document.getElementById('alertText').value
);" />
</form>
https://www.cs.odu.edu/~mweigle/cs312/examples/js/passing-args.html 27
Outline
◆ What is JavaScript?
◆ JavaScript Syntax
◆ JavaScript and HTML DOM
◆ Event Handlers
◆ Pop-Ups and Functions
◆ Form Validation
◆ More Examples
28
Form Validation
<form method="post" action="..." onsubmit="return validateform()">
<input type="email" id="email1" name="email1"/>
<input type="email" id="email2" name="email2"/>
<p id="message"></p>
<input type="submit" value="Submit"/>
</form>
function validateForm(){
var email1 = document.getElementById('email1').value;
var email2 = document.getElementById('email2').value;
if (email1 != email2) {
document.getElementById('message').innerHTML =
"Email addresses must match";
return false;
} else {
document.getElementById('message').innerHTML = "";
return true;
}
}
https://www.cs.odu.edu/~mweigle/cs312/rgrove/javascript/validateform.html 29
Outline
◆ What is JavaScript?
◆ JavaScript Syntax
◆ JavaScript and HTML DOM
◆ Event Handlers
◆ Pop-Ups and Functions
◆ Form Validation
◆ More Examples
30
More Examples
https://www.cs.odu.edu/~mweigle/cs312/examples/index.html#javascript
31