2. Review: JavaScript vs Java
• interpreted, not compiled
• more relaxed syntax and rules
• fewer and "looser" data types
• variables don't need to be declared
• errors often silent (few exceptions)
• key construct is the function rather than the class
• "first-class" functions are used in many situations
• contained within a web page and integrates with its HTML/CSS content
3. Review: External Linking
• <script src="filename" type="text/javascript"></script
• script tag should be placed in HTML page's head
• script code is stored in a separate .js file
• JS code can be placed directly in the HTML file's body or head (like CSS
4. Common Uses of JavaScript
• Form validation
• Page embellishments and special effects
• Navigation systems
• Basic math calculations
• Dynamic content manipulation
• Sample applications
• Dashboard widgets in Mac OS X, Google Maps, Philips universal remotes, Writely word
processor, hundreds of others…
5. Example 1: Add Two Numbers
<html>
…
<p> … </p>
<script>
var num1, num2, sum
num1 = prompt("Enter first number")
num2 = prompt("Enter second number")
sum = parseInt(num1) + parseInt(num2)
alert("Sum = " + sum)
</script>
…
</html>
6. Example 2: Browser Events
<script type="text/JavaScript">
function whichButton(event) {
if (event.button==1) {
alert("You clicked the left mouse button!") }
else {
alert("You clicked the right mouse button!")
}}
</script>
…
<body onmousedown="whichButton(event)">
…
</body>
Mouse event causes page-
defined function to be
called
Other events: onLoad, onMouseMove, onKeyPress, onUnLoad
7. Example 3: Page Manipulation
• Some possibilities
• createElement(elementName)
• createTextNode(text)
• appendChild(newChild)
• removeChild(node)
• Example: add a new list item
var list = document.getElementById('t1')
var newitem = document.createElement('li')
var newtext = document.createTextNode(text)
list.appendChild(newitem)
newitem.appendChild(newtext)
This uses the browser
Document Object Model
(DOM). We will focus on
JavaScript as a language,
not its use in the browser
8. Document Object Model (DOM)
• HTML page is structured data
• DOM provides representation of this hierarchy
• Examples
• Properties: document.alinkColor, document.URL, document.forms[ ], document.links[ ],
document.anchors[ ], …
• Methods: document.write(document.referrer)
• These change the content of the page!
• Also Browser Object Model (BOM)
• Window, Document, Frames[], History, Location, Navigator (type and version of browser)
9. Hello World in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Hello World Example</title>
</head>
<body>
<script type="text/javascript">
<!--
document.write("<h1>Hello, world!</h1>");
//-->
</script>
</body>
</html>
10. Number properties/methods
Number object "static" properties
Number.MAX_VALUE largest possible number, roughly 10308
Number.MIN_VALUE smallest positive number, roughly 10-324
Number.NaN Not-a-Number; result of invalid computations
Number.POSITIVE_INFINITY infinity; result of 1/0
Number.NEGATIVE_INFINITY negative infinity; result of -1/0
11. Number properties/methods
Number instance methods
.toString([base]) convert a number to a string with optional base
.toFixed(digits) fixed-point real with given # digits past decimal
.toExponential(digits) convert a number to scientific notation
.toPrecision(digits) floating-point real, given # digits past decimal
12. Number properties/methods
global methods related to numbers
isNaN(expr) true if the expression evaluates to NaN
isFinite(expr) true if expr is neither NaN nor an infinity
13. Math properties/methods
Math.E e, base of natural logarithms: 2.718...
Math.LN10, Math.LN2,
Math.LOG2E, Math.LOG10E
natural logarithm of 10 and 2;
logarithm of e in base 2 and base 10
Math.PI , circle's circumference/diameter: 3.14159...
Math.SQRT1_2, Math.SQRT2 square roots of 1/2 and 2
Math.abs(n) absolute value
Math.acos/asin/atan(n) arc-sin/cosine/tangent of angle in radians
Math.ceil(n) ceiling (rounds a real number up)
Math.cos/sin/tan(n) sin/cosine/tangent of angle in radians
Math.exp(n) en, e raised to the nth power
Math.floor(n) floor (rounds a real number down)
Math.log(n) natural logarithm (base e)
Math.max/min(a, b...) largest/smallest of 2 or more numbers
Math.pow(x, y) xy, x raised to the yth power
Math.random() random real number k in range 0 ≤ k < 1
Math.round(n) round number to nearest whole number
Math.sqrt(n) square root
14. String methods
String.fromCharCode(expr) converts ASCII integer → String
.charAt(index) returns character at index, as a String
.charCodeAt(index) returns ASCII value at a given index
.concat(str...) returns concatenation of string(s) to this one
.indexOf(str[,start])
.lastIndexOf(str[,start])
first/last index at which given string begins in this string, optionally starting
from given index
.match(regexp) returns any matches for this string against the given string or regular
expression ("regex")
.replace(old, new) replaces first occurrence of old string or regular expr. with new string (use
regex to replace all)
.search(regexp) first index where given regex occurs
.slice(start, end)
.substring(start, end)
substr. from start (inclusive) to end (exclusive)
.split(delimiter[,limit]) break apart a string into an array of strings
.toLowerCase()
.toUpperCase()
return new string in all upper/lowercase
15. Dealing with old browsers
• Some old browsers do not recognize script tags
• These browsers will ignore the script tags but will display the included JavaScript
• To get old browsers to ignore the whole thing, use:
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
• The <!-- introduces an HTML comment
• To get JavaScript to ignore the HTML close comment, -->, the // starts a JavaScript comment,
which extends to the end of the line
16. Exception Handling
• Exception handling in JavaScript is almost the same as in Java
• throw expression creates and throws an exception
• The expression is the value of the exception, and can be of any type (often, it's a literal String)
• try {
statements to try
} catch (e) { // Notice: no type declaration for e
exception-handling statements
} finally { // optional, as usual
code that is always executed
}
• With this form, there is only one catch clause
17. Exception Handling
• try {
statements to try
} catch (e if test1) {
exception-handling for the case that test1 is true
} catch (e if test2) {
exception-handling for when test1 is false and test2 is true
} catch (e) {
exception-handling for when both test1and test2 are false
} finally { // optional, as usual
code that is always executed
}
• Typically, the test would be something like
e == "InvalidNameException"
18. JavaScript Warnings
• JavaScript is a big, complex language
• We’ve only scratched the surface
• It’s easy to get started in JavaScript, but if you need to use it heavily, plan to invest time in learning it well
• Write and test your programs a little bit at a time
• JavaScript is not totally platform independent
• Expect different browsers to behave differently
• Write and test your programs a little bit at a time
• Browsers aren’t designed to report errors
• Don’t expect to get any helpful error messages
• Write and test your programs a little bit at a time
19. JS Pop Up Type 1: Alert Box
• An alert box is often used if you want to make sure
information comes through to the user.
• When an alert box pops up, the user will have to
click "OK" to proceed.
20. Alert Box Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>
21. JS Pop Up Type 2: Confirm Box
• A confirm box is often used if you want the user to verify or accept something.
• When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
• If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
22. Confirm Box Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
23. JS Pop Up Type 3: Prompt Box
• A prompt box is often used if you want the user to input a value before entering a
page.
• When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.
• If the user clicks "OK" the box returns the input value. If the user clicks "Cancel"
the box returns null.
24. Prompt Box Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let text;
let person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
25. Two Input Prompt Example
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
<!--
var favcolour, favcolour2;
favcolour = prompt("What is your Favorite colour?");
favcolour2 = prompt("How about your second favorite colour?");
document.write(favcolour," ", favcolour2);
// -->
</script>
</body>
</html>
26. JavaScript Popups
<script>
// JavaScript popup window function
function basicPopup(url) {
popupWindow =
window.open(url,'popUpWindow','height=300,width=700,left=50,top=50,resizable=yes,scrollbars=
yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes')
}
</script>
<a href="http://courses.shu.edu/BITM3730/marinom6/" onclick="basicPopup(this.href);return
false">Click here to visit my website</a>
27. JavaScript Assignment
• Combine your skills from CSS [onclick] and your JS skills to create an HTML
file called popup.html that when you click an onclick it will open your
courses.shu.edu website as a popup.