<!--#include virtual="../s5/commontop.html" -->
<title>Lecture 7: More Events & Creating Elements — INFO 343 Autumn 2012</title>
</head>
<body>
<div class="layout">
<div id="controls"><!-- DO NOT EDIT --></div>
<div id="currentSlide"><!-- DO NOT EDIT --></div>
<div id="header"></div>
<div id="footer">
<h1>INFO 343 Lecture 7</h1>
<h2>More Events & Creating Elements</h2>
</div>
</div>
<div class="presentation">
<div class="slide">
<h1>More Events & Creating Elements</h1>
<h3>Lecture 7</h3>
<!-- <h4>Reading: 8.3.5, 9.2.3, 9.2.5</h4> -->
<p class="license">
Except where otherwise noted, the contents of this presentation are Copyright 2010 Marty Stepp, Jessica Miller, and/or Morgan Doocy.
</p>
<div class="w3c">
<a href="http://validator.w3.org/check/referer"><img src="../s5/images/w3c-xhtml11.png" alt="Valid XHTML 1.1" /></a>
<a href="http://jigsaw.w3.org/css-validator/check/referer"><img src="../s5/images/w3c-css.png" alt="Valid CSS!" /></a>
</div>
</div>
<div class="slide titleslide">
<h1>The <code>this</code> keyword</h1>
<ul>
<li><strong>The <code>this</code> keyword</strong></li>
<li>More Events</li>
<li>Creating & Injecting Elements</li>
<li>Timers</li>
</ul>
</div>
<div class="slide">
<h1>
The keyword <code>this</code>
<span class="readingsection">(8.1.3)</span>
</h1>
<pre class="syntaxtemplate js">
this.<var>fieldName</var> <span class="comment">// access field</span>
this.<var>fieldName</var> = <var>value</var>; <span class="comment">// modify field</span>
this.<var>methodName</var>(<var>parameters</var>); <span class="comment">// call method</span>
</pre>
<ul>
<li>
all JavaScript code actually runs inside of an object
</li>
<li>
by default, code runs inside the global <code>window</code> object
<ul>
<li>
all global variables and functions you declare become part of <code>window</code>
</li>
</ul>
</li>
<li>
the <code>this</code> keyword refers to the current object
</li>
</ul>
</div>
<div class="slide">
<h1>
Event handler binding
</h1>
<div class="example">
<pre class="examplecode js">
function pageLoad() {
<em>$("#ok").click(okayClick);</em> <span class="comment">// bound to okButton here</span>
}
function okayClick() { <span class="comment">// okayClick knows what DOM object</span>
$(<em>this</em>).text("booyah"); <span class="comment">// it was called on</span>
}
$(document).ready(pageLoad);
</pre>
<div class="exampleoutput">
<button id="ok" onclick="this.innerHTML = 'booyah';">OK</button>
</div>
</div>
<ul>
<li>event handlers attached unobtrusively are <span class="term">bound</span> to the element</li>
<li>inside the handler, that element becomes <code>this</code> (rather than the <code>window</code>)</li>
<li>with jQuery, wrap <code>this</code> inside the jQuery function (<code>$</code>) to “bless” it with jQuery methods</li>
</ul>
</div>
<div class="slide">
<h1>Fixing redundant code with <code>this</code></h1>
<pre class="examplecode html">
<fieldset>
<label><input type="radio" name="ducks" id="huey" <em>value="Huey"</em> /> Huey</label>
<label><input type="radio" name="ducks" id="dewey" <em>value="Dewey"</em> /> Dewey</label>
<label><input type="radio" name="ducks" id="louie" <em>value="Louie"</em> /> Louie</label>
</fieldset>
</pre>
<pre class="examplecode js">
function processDucks() {
<del class="bad"> if ($("#huey").is(':checked')) {
alert("Huey is checked!");
} else if ($("#dewey").is(':checked')) {
alert("Dewey is checked!");
} else { // $("#louie").is(':checked')
alert("Louie is checked!");
}</del>
<span class="errorfixed">alert(<em>$(this).val() + </em>" is checked!");</span>
}
</pre>
<ul>
<li>if the same function is assigned to multiple elements, each gets its own bound copy</li>
</ul>
</div>
<div class="slide titleslide">
<h1>More Events</h1>
<ul>
<li>The <code>this</code> keyword</li>
<li><strong>More Events</strong></li>
<li>Creating & Injecting Elements</li>
<li>Timers</li>
</ul>
</div>
<div class="slide">
<h1>JavaScript events</h1>
<table class="standard">
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onabort.asp">abort</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onblur.asp">blur</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onchange.asp">change</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onclick.asp">click</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_ondblclick.asp">dblclick</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onerror.asp">error</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onfocus.asp">focus</a></code>
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onkeydown.asp">keydown</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onkeypress.asp">keypress</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onkeyup.asp">keyup</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onload.asp">load</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onmousedown.asp">mousedown</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onmousemove.asp">mousemove</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onmouseout.asp">mouseout</a></code>
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onmouseover.asp">mouseover</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onmouseup.asp">mouseup</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onreset.asp">reset</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onresize.asp">resize</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onselect.asp">select</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onsubmit.asp">submit</a></code>
</td>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onunload.asp">unload</a></code>
</td>
</tr>
</table>
<ul>
<li>
the <code>click</code> event (<code>onclick</code>) is just one of many events that can be handled
</li>
<li>
<strong>problem</strong>: events are tricky and have <a href="http://www.quirksmode.org/js/introevents.html">incompatibilities</a> across browsers
<ul>
<li>
reasons: fuzzy W3C event specs; IE disobeying web standards; etc.
</li>
</ul>
</li>
<li>
<strong>solution</strong>: jQuery includes many event-related features and fixes
</li>
</ul>
</div>
<div class="slide">
<h1>The <code>event</code> object</h1>
<pre class="syntaxtemplate js">
function <var>name</var>(<em>event</em>) {
<span class="comment">// an event handler function ...</span>
}
</pre>
<ul>
<li>
Event handlers can accept an optional parameter to represent the event that is occurring. Event objects have the following properties / methods:
</li>
</ul>
<table class="standard">
<tr>
<th>
method / property name
</th>
<th>
description
</th>
</tr>
<tr>
<td>
<code>type</code>
</td>
<td>
what kind of event, such as <code>"click"</code> or <code>"mousedown"</code>
</td>
</tr>
<tr>
<td>
<a href=""><code>target</code></a>
</td>
<td>
the element on which the event occurred
</td>
</tr>
<tr>
<td>
<a href=""><code>relatedTarget</code></a>
</td>
<td>
the other element involved, if any (e.g., element moved into)
</td>
</tr>
<tr>
<td>
<a href=""><code>preventDefault()</code></a>
</td>
<td>
stops the event from occurring on this element
</td>
</tr>
<tr>
<td>
<a href=""><code>stopPropagation()</code></a>
</td>
<td>
prevents the event from propagating to parent elements
</td>
</tr>
<!-- <tr>
<td>
<a href="http://prototypejs.org/api/event/stopObserving"><code>stopObserving()</code></a>
</td>
<td>
removes an event handler
</td>
</tr> -->
</table>
<!-- <ul class="aside" style="list-style-type: none">
<li>
* replaces non-standard <code>srcElement</code> and <code>which</code> properties
</li>
<li>
** replaces non-standard <code>return false;</code>, <code>stopPropagation</code>, etc.
</li>
</ul> -->
</div>
<div class="slide">
<h1>
Mouse events
<span class="readingsection">(9.2.2)</span>
</h1>
<table class="standard">
<caption>clicking</caption>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onclick.asp">click</a></code>
</td>
<td>
user presses/releases mouse button on the element
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_ondblclick.asp">dblclick</a></code>
</td>
<td>
user presses/releases mouse button twice on the element
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onmousedown.asp">mousedown</a></code>
</td>
<td>
user presses down mouse button on the element
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onmouseup.asp">mouseup</a></code>
</td>
<td>
user releases mouse button on the element
</td>
</tr>
</table>
<table class="standard">
<caption>movement</caption>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onmouseover.asp">mouseover</a></code>
</td>
<td>
mouse cursor enters the element's box
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onmouseout.asp">mouseout</a></code>
</td>
<td>
mouse cursor exits the element's box
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onmousemove.asp">mousemove</a></code>
</td>
<td>
mouse cursor moves around within the element's box
</td>
</tr>
</table>
</div>
<div class="slide">
<h1>Mouse event objects</h1>
<p>
The <code>event</code> passed to a mouse handler has these properties:
</p>
<div class="rightfigure" style="width: 30%">
<img src="images/figure_2_mouse_events.png" alt="mouse event" style="width: 100%" />
</div>
<table class="standard">
<tr>
<th>
property/method
</th>
<th>
description
</th>
</tr>
<tr>
<td>
<code>clientX</code>, <code>clientY</code>
</td>
<td>
coordinates in <em>browser window</em>
</td>
</tr>
<tr>
<td>
<code>screenX</code>, <code>screenY</code>
</td>
<td>
coordinates in <em>screen</em>
</td>
</tr>
<tr>
<td>
<code>offsetX</code>, <code>offsetY</code>
</td>
<td>
coordinates in <em>element</em> (non-standard)
</td>
</tr>
<tr>
<td>
<code>pageX</code>, <code>pageY</code>
</td>
<td>
coordinates in <em>entire web page</em>
</td>
</tr>
<!-- <tr>
<td>
<a href="http://prototypejs.org/api/event/pointerX"><code>pointerX()</code></a>, <br />
<a href="http://prototypejs.org/api/event/pointerY"><code>pointerY()</code></a> *
</td>
<td>
coordinates in <em>entire web page</em>
</td>
</tr> -->
<tr>
<td>
<a href=""><code>which</code></a>
</td>
<td>
for click events, can be used to determine which mouse button was used
</td>
</tr>
</table>
<!-- <ul class="aside" style="list-style-type: none">
<li>
* replaces non-standard properties <code>pageX</code> and <code>pageY</code>
</li>
<li>
** replaces non-standard properties <code>button</code> and <code>which</code>
</li>
</ul> -->
</div>
<div class="slide">
<h1>Mouse event example</h1>
<div class="example">
<pre class="examplecode html">
<pre id="target">Move the mouse over me!</pre>
</pre>
<pre class="examplecode js">
$(document).ready(function() {
$("#target").mousemove(showCoords);
});
function showCoords(<em>event</em>) {
$("#target").text(
"pointer: (" + <em>event.pageX</em> + ", " + <em>event.pageY</em> + ")\n"
+ "screen : (" + <em>event.screenX</em> + ", " + <em>event.screenY</em> + ")\n"
+ "client : (" + <em>event.clientX</em> + ", " + <em>event.clientY</em> + ")");
}
</pre>
<div class="exampleoutput">
<pre onmousemove="this.innerHTML = 'pointer: (' + event.pageX + ', ' + event.pageY + ')\n' + 'screen : (' + event.screenX + ', ' + event.screenY + ')\n' + 'client : (' + event.clientX + ', ' + event.clientY + ')';">
Move the mouse over me!</pre>
</div>
</div>
</div>
<div class="slide">
<h1>
Page/window events
<span class="readingsection">(9.2.5)</span>
</h1>
<table class="standard">
<tr>
<th>name</th><th>description</th>
</tr>
<tr>
<td>
<code><a href="">$(document).ready()</a></code>,
<code><a href="">$(window).unload()</a></code>
</td>
<td>
the browser loads/exits the page
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onresize.asp">$(window).resize()</a></code>
</td>
<td>
the browser window is resized
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onerror.asp">$(window).error()</a></code>
</td>
<td>
an error occurs when loading a document or an image
</td>
</tr>
<!-- <tr>
<td>
<code>contextmenu</code>
</td>
<td>
the user right-clicks to pop up a context menu
</td>
</tr> -->
</table>
<!-- <ul>
<li>
The above can be handled on the <code>window</code> object. An alternative to <code>window.onload</code>:
</li>
</ul> -->
<pre class="examplecode js">
<del>window.onload = function() { ... };</del>
<em>$(document).ready</em>(function() {
<span class="comment">// attach event handlers, etc.</span>
});
</pre>
</div>
<div class="slide">
<h1>
Keyboard/text events
<span class="readingsection">(9.2.3)</span>
</h1>
<table class="standard">
<tr>
<th>name</th>
<th>description</th>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onkeydown.asp">keydown</a></code>
</td>
<td>
user presses a key while this element has keyboard focus
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onkeyup.asp">keyup</a></code>
</td>
<td>
user releases a key while this element has keyboard focus
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onkeypress.asp">keypress</a></code>
</td>
<td>
user presses and releases a key while this element has keyboard focus
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onfocus.asp">focus</a></code>
</td>
<td>
this element gains keyboard focus
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onblur.asp">blur</a></code>
</td>
<td>
this element loses keyboard focus
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/jsref/jsref_onselect.asp">select</a></code>
</td>
<td>
this element's text is selected or deselected)
</td>
</tr>
</table>
<ul>
<li>
<span class="term">focus</span>: the attention of the user's keyboard (given to one element at a time)</li>
</li>
</ul>
</div>
<div class="slide">
<h1>Keyboard event objects</h1>
<table class="standard">
<tr>
<th>
property name
</th>
<th>
description
</th>
</tr>
<tr>
<td>
<code>keyCode</code>
</td>
<td>
ASCII integer value of key that was pressed <br />
(convert to char with <a href="http://www.quirksmode.org/js/keys.html"><code>String.fromCharCode</code></a>)
</td>
</tr>
<tr>
<td>
<code>altKey</code>, <code>ctrlKey</code>, <code>shiftKey</code>
</td>
<td>
<code>true</code> if Alt/Ctrl/Shift key is being held
</td>
</tr>
</table>
<ul>
<li>Consider mapping global “constants” for certain key codes:
<ul>
<li>Backspace: 8</li>
<li>Escape: 27</li>
<li>Enter: 13</li>
<li><a href="http://en.wikipedia.org/wiki/Control_character#In_ASCII">Full list</a></li>
</ul>
</li>
<li>
issue: if the event you attach your listener to doesn't have the focus, you won't hear the event
<ul>
<li>
possible solution: attach key listener to entire page body, outer element, etc.
</li>
</ul>
</li>
</ul>
</div>
<div class="slide titleslide">
<h1>Creating & Injecting Elements</h1>
<ul>
<li>The <code>this</code> keyword</li>
<li>More Events</li>
<li><strong>Creating & Injecting Elements</strong></li>
<li>Timers</li>
</ul>
</div>
<div class="slide">
<h1>
Creating new nodes
<span class="readingsection">(8.3.5)</span>
</h1>
<table class="standard">
<tr>
<th>
name
</th>
<th>
description
</th>
</tr>
<tr>
<td>
<code>$(document.createElement("<var>tagName</var>"))</code>
</td>
<td>
creates and returns a new empty DOM node representing an element of that type<br/>
<small>(wrapped in <code>$</code> to bless with jQuery stuff)
</td>
</tr>
<tr>
<td>
<code>$('<<var>tagName</var>>', { <var>attributes…</var> })</code>
</td>
<td>
creates a new DOM element with the given attributes using jQuery
</td>
</tr>
</table>
<pre class="examplecode js">
<span class="comment">// create a new <h2> node</span>
var $newHeading = <em>$(document.createElement("h2"))</em>;
$newHeading.text("This is a heading");
$newHeading.css('color', "green");
<span class="comment">// equivalent - one statement, more confusing</span>
var $anotherNewHeading = $('<h2>', <em>{
'text': 'This is another heading'
}</em>).css('color', 'green');
</pre>
</div>
<div class="slide">
<h1>Injecting a new element into the page</h1>
<ul>
<li>Merely creating a node will not make it appear on-screen!</li>
<li>Have to inject it into the page somewhere…</li>
</ul>
<pre class="syntaxtemplate js">
<var>$jQueryObj</var>.appendTo('<var>target</var>');
</pre>
<pre class="examplecode js">
<span class="comment">// create a new <a> node</span>
var $newLink = $('<a>', { href: 'http://ischool.uw.edu/', text: 'My School' });
$newLink.appendTo('#nav li:last-child');
<span class="comment">// equivalent - single statement</span>
$('<a>', {
href: 'http://ischool.uw.edu',
text: 'My School'
}).appendTo('#nav li:last-child');
<span class="comment">// equivalent - using .attr() and .text() instead</span>
$('<a>').attr('href', 'http://ischool.uw.edu/').text('My School')
.appendTo('#nav li:last-child');
</pre>
</div>
<div class="slide" id="thisslide" onclick="this.innerHTML += '<span>A span!</span>'">
<h1>Injecting a new element into the page (cont’d)</h1>
<p>Can inject at several different locations using jQuery…</p>
<table class="standard" style="font-size: 90%">
<tr>
<th>
name
</th>
<th>
description
</th>
</tr>
<tr>
<td>
<code><var>$target</var>.<a href="http://api.jquery.com/prepend/">prepend</a>(<var>$newObj</var>)</code>,
<code><var>$target</var>.<a href="http://api.jquery.com/append/">append</a>(<var>$newObj</var>)</code>,
</td>
<td>
injects <var>$newObj</var> before/after <var>$target</var>’s first/last child
</td>
</tr>
<tr>
<td>
<code><var>$newObj</var>.<a href="http://api.jquery.com/prependTo/">prependTo</a>(<var>target</var>)</code>,
<code><var>$newObj</var>.<a href="http://api.jquery.com/appendTo/">appendTo</a>(<var>target</var>)</code>
</td>
<td>
same as the above, in opposite direction<br/>
<small>(<var>target</var> can be a jQuery object or selector string)</small>
</td>
</tr>
<tr>
<td>
<code><var>$target</var>.<a href="http://api.jquery.com/before/">before</a>(<var>$newObj</var>)</code>,
<code><var>$target</var>.<a href="http://api.jquery.com/after/">after</a>(<var>$newObj</var>)</code>
</td>
<td>
injects <var>$newObj</var> before/after <var>$target</var> (as its previous/next sibling)
</td>
</tr>
<tr>
<td>
<code><var>$newObj</var>.<a href="http://api.jquery.com/insertBefore/">insertBefore</a>(<var>target</var>)</code>,
<code><var>$newObj</var>.<a href="http://api.jquery.com/insertAfter/">insertAfter</a>(<var>target</var>)</code>
</td>
<td>
same as above, in opposite direction<br/>
<small>(<code>target</code> can be jQuery object or selector string)</small>
</td>
</tr>
</table>
<pre class="examplecode js">
var $span = <em>$('<span>').text('A span!').appendTo('#main')</em>;
</pre>
</div>
<!-- <div class="slide" id="thisslide" onclick="var p = document.createElement('p'); p.innerHTML = 'A paragraph!'; this.appendChild(p);">
<h1>Injecting a new element into the page (converse)</h1>
<p>Reverse queries:</p>
<table class="standard">
<tr>
<th>
name
</th>
<th>
description
</th>
</tr>
<tr>
<td>
<code><var>target</var>.<a href="">before</a>(<var>$newjQueryObj</var>)</code>,
<code><var>target</var>.<a href="">after</a>(<var>$newjQueryObj</var>)</code>
</td>
<td>
injects <var>$newjQueryObj</var> before/after <var>target</var>’s first/last child
</td>
</tr>
<tr>
<td>
<code><var>target</var>.<a href="">prepend</a>(<var>$newjQueryObj</var>)</code>,
<code><var>target</var>.<a href="">append</a>(<var>$newjQueryObj</var>)</code>
</td>
<td>
injects <var>$newjQueryObj</var> before/after <var>target</var>’s first/last child
</td>
</tr>
</table>
<pre class="examplecode js">
var $p = <em>$('<p>').text('A paragraph!').appendTo('#main')</em>;
</pre>
</div> -->
<div class="slide">
<h1>Removing a node from the page</h1>
<pre class="examplecode js" onclick="var li = document.getElementById('killme'); li.parentNode.removeChild(li);">
function slideClick() {
$('li').each(function() {
if ($(this).text().indexOf("converse") >= 0) {
<em>$(this).remove();</em>
}
});
}
</pre>
<ul>
<li>
replace with something else: <code><var>$oldObj</var>.replaceWith(<var>$newObj</var>)</code>
<ul>
<li id="killme">converse: <code><var>$newObj</var>.replaceAll('<var>target</var>')</code></li>
</ul>
</li>
<li>
remove temporarily (when going to reinsert) using <code><var>$jQueryObj</var>.detach()</code>
</li>
</ul>
</div>
<div class="slide">
<h1>DOM versus <code>innerHTML</code> hacking</h1>
<p>Why not just code the previous example this way?</p>
<pre class="examplecode js">
function slideClick() {
document.getElementById("thisslide").<em>innerHTML += "<p>A paragraph!</p>"</em>;
}
</pre>
<div class="incremental">
<ul>
<li>Imagine that the new node is more complex:
<ul>
<li>ugly: bad style on many levels (e.g. JS code embedded within HTML)</li></li>
<li>error-prone: must carefully distinguish <code>"</code> and <code>'</code></li>
<li>can only add at beginning or end, not in middle of child list</li>
</ul>
</li>
</ul>
<pre class="examplecode js">
function slideClick() {
this.innerHTML += <em>"<p style='color: red; " +
"margin-left: 50px;' " +
"onclick='myOnClick();'>" +
"A paragraph!</p>"</em>;
}
</pre>
</div>
</div>
<div class="slide">
<h1>Example: Dynamically-created list of links</h1>
<div class="example">
<pre class="examplecode js">
var goliaths = { 'http://www.google.com/': 'Google',
'http://www.apple.com': 'Apple',
'http://www.microsoft.com/': 'Microsoft' };
$.each(goliaths, function(url, name) {
var $a = $('<a>').attr('href', url).text(name);
var $li = $('<li>');
$li.append($a);
$('ul#links').append($li);
});
</pre>
<div class="exampleoutput">
<ul>
<li><a href="http://www.google.com/">Google</a></li>
<li><a href="http://www.apple.com/">Apple</a></li>
<li><a href="http://www.microsoft.com/">Microsoft</a></li>
</ul>
</div>
</div>
<ul>
<li>Can use <code>.append()</code> etc. to inject content into other jQuery objects, and then inject those objects into the page.</li>
</ul>
</div>
<div class="slide titleslide">
<h1>Timers</h1>
<ul>
<li>The <code>this</code> keyword</li>
<li>More Events</li>
<li>Creating & Injecting Elements</li>
<li><strong>Timers</strong></li>
</ul>
</div>
<div class="slide">
<h1>
Timer events
<span class="readingsection">(9.2.6)</span>
</h1>
<div class="topfigure" style="width: 12%">
<img src="images/timer.gif" alt="timer" style="width: 100%" />
</div>
<table class="standard">
<tr>
<th>
method
</th>
<th>
description
</th>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/htmldom/met_win_settimeout.asp">setTimeout</a>(<var>function</var>, <var>delayMS</var>);</code>
</td>
<td>
arranges to call given function after given delay in ms
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/htmldom/met_win_setinterval.asp">setInterval</a>(<var>function</var>, <var>delayMS</var>);</code>
</td>
<td>
arranges to call function repeatedly every <var>delayMS</var> ms
</td>
</tr>
<tr>
<td>
<code><a href="http://www.w3schools.com/htmldom/met_win_cleartimeout.asp">clearTimeout</a>(<var>timerID</var>);</code> <br />
<code><a href="http://www.w3schools.com/htmldom/met_win_clearinterval.asp">clearInterval</a>(<var>timerID</var>);</code>
</td>
<td>
stops the given timer so it will not call its function
</td>
</tr>
</table>
<ul>
<li>
both <code>setTimeout</code> and <code>setInterval</code> return an ID representing the timer
<ul>
<li>
this ID can be passed to <code>clearTimeout</code>/<code>Interval</code> later to stop the timer
</li>
</ul>
</li>
</ul>
</div>
<div class="slide">
<h1>
<code>setTimeout</code></a> example</a>
</h1>
<div class="example">
<pre class="examplecode html">
<button id="button">Click me!</button>
<span <em>id="output"</em>></span>
</pre>
<pre class="examplecode examplecode2 js">
$(document).ready(function() {
$("#button").click(<em>delayMsg</em>);
});
function delayMsg() {
<em>setTimeout(booyah, 5000)</em>;
$("#output").text("Wait for it...");
}
function booyah() { <span class="comment">// called when the timer goes off</span>
$("#output").text("BOOYAH!");
}
</pre>
<div class="exampleoutput">
<button onclick="document.getElementById('output').innerHTML = 'Wait for it...'; setTimeout("document.getElementById('output').innerHTML = 'BOOYAH!';", 5000)">Click me!</button>
<span id="output"></span>
</div>
</div>
</div>
<div class="slide">
<h1>
<code>setInterval</code> example
</h1>
<div class="example">
<pre class="examplecode examplecode2 js">
<em>var timer = null;</em> <span class="comment">// stores ID of interval timer</span>
function delayMsg2() {
if (timer == null) {
<em>timer = setInterval(rudy, 1000)</em>;
} else {
<em>clearInterval(timer)</em>;
timer = null;
}
}
function rudy() { <span class="comment">// called each time the timer goes off</span>
$("#output").first().innerHTML += " Rudy!";
}
</pre>
<div class="exampleoutput">
<script type="text/javascript">
window.timer = null;
window.delayMsg2 = function() {
if (timer == null) {
timer = setInterval(rudy, 1000);
} else {
clearInterval(timer);
timer = null;
}
};
window.rudy = function() {
document.getElementById("output2").innerHTML += " Rudy!";
};
</script>
<button onclick="delayMsg2();">Click me!</button>
<span id="output2"></span>
</div>
</div>
</div>
<div class="slide">
<h1>Passing parameters to timers</a></h1>
<div class="example">
<pre class="examplecode js">
function delayedMultiply() {
<span class="comment">// 6 and 7 are passed to multiply when timer goes off</span>
setTimeout(multiply, 2000<em>, 6, 7</em>);
}
function multiply(<em>a, b</em>) {
alert(a * b);
}
</pre>
<div class="exampleoutput insertoutput">
<button onclick="delayedMultiply();">Click me</button>
</div>
</div>
<ul>
<li>any parameters after the delay are eventually passed to the timer function
<ul>
<li>doesn't work in IE6; must create an intermediate function to pass the parameters</li>
</ul>
</li>
<li>
why not just write this?
<pre class="examplecode js">
setTimeout(<em>multiply(6 * 7)</em>, 2000);
</pre>
</li>
</ul>
</div>
<div class="slide">
<h1>Common timer errors</h1>
<ul>
<li>
many students mistakenly write <code>()</code> when passing the function
<pre class="examplecode js">
<del>setTimeout(booyah(), 2000);</del>
setTimeout(<em>booyah</em>, 2000);
<del>setTimeout(multiply(num1 * num2), 2000);</del>
setTimeout(<em>multiply</em>, 2000<em>, num1, num2</em>);
</pre>
<ul>
<li>what does it actually do if you have the <code>()</code> ?</li>
<li class="incremental">it calls the function immediately, rather than waiting the 2000ms!</li>
</ul>
</li>
</ul>
</div>
<!--#include virtual="../s5/commonbottom.html" -->