Professional Documents
Culture Documents
15-UnobtrusiveJS
15-UnobtrusiveJS
CS380
The six global DOM objects
2
CS380
The window object
3
getElementsByTagName
CS380
The location object
5
CS380
The navigator object
6
CS380
The screen object
7
CS380
The history object
8
CS380
Unobtrusive JavaScript
9
CS380
Unobtrusive JavaScript
10
CS380
Obtrusive event handlers (bad)
11
CS380
Attaching an event handler in
12
JavaScript code
// where element is a DOM element object
element.event = function;
JS
$("ok").onclick = okayClick;
JS
<head>
<script src="myfile.js" type="text/javascript"></script>
</head>
<body> ... </body> HTML
// global code
var x = 3;
function f(n) { return n + 1; }
function g(n) { return n - 1; }
x = f(x); JS
<head>
<script src="myfile.js" type="text/javascript"></script>
</head>
<body> ... </body> HTML
// global code
var x = 3;
function f(n) { return n + 1; }
function g(n) { return n - 1; }
x = f(x); JS
CS380
Common unobtrusive JS errors
18
CS380
Anonymous functions
19
function(parameters) {
statements;
}
JS
window.onload = function() {
var okButton = document.getElementById("ok");
okButton.onclick = okayClick;
};
function okayClick() {
alert("booyah");
}
JS
CS380
The keyword this
21
JS
function pageLoad() {
$("ok").onclick = okayClick; // bound to okButton
here
}
function okayClick() { // okayClick knows what DOM object
this.innerHTML = "booyah"; // it was called on
}
window.onload = pageLoad;
JS
<h1>Tip Calculator</h1>
<div>
$<input id="subtotal" type="text" size= "5" /> subtotal
<br />
<button id="tenpercent">10%</button>
<button id="fifteenpercent"> 15%</button>
<button id="eighteenpercent"> 18%</button>
<span id="total"></span>
</div> HTML
window.onload = function() {
$("tenpercent").onclick = computeTip;
}
function computeTip{
var subtotal = parseFloat($("subtotal").value);
var tipAmount = subtotal*0.1;//Add this code
$("total").innerHTML = "Tip: $" + tipAmount;
} JS