WEB STANDARDS CREATIVITY
WEB STANDARDS CREATIVITY
WEB STANDARDS CREATIVITY
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
The JavaScript<br />
When expand_collapse.js is included on the page, it sets up a page load listener, and then iterates through each of the<br />
modules and inserts the appropriate HTML elements:<br />
addLoadListener(initExpandCollapse);<br />
function initExpandCollapse()<br />
{<br />
var modules = [document.getElementById("modules1"), document.getElementById("modules2")];<br />
for (var i in modules)<br />
{<br />
var h2s = modules[i].getElementsByTagName("h2");<br />
for (var i = 0; i < h2s.length; i++)<br />
{<br />
var newA = document.createElement("a");<br />
newA.setAttribute("href", "#");<br />
newA.setAttribute("title", "Expand/Collapse");<br />
attachEventListener(newA, "mousedown", mousedownExpandCollapse,false);<br />
newA.onclick = clickExpandCollapse;<br />
var newImg = document.createElement("img");<br />
newImg.setAttribute("src", "images/min_max.gif");<br />
newImg.setAttribute("alt", "Expand/Collapse");<br />
newA.appendChild(newImg);<br />
h2s[i].appendChild(newA);<br />
}<br />
}<br />
return true;<br />
};<br />
The page load listener is added using the addLoadListener() function from the same event_listeners.js file as the<br />
resolution-dependent layout example and calls initExpandCollapse() when the page is ready.<br />
initExpandCollapse() starts by creating an array of the module elements of interest, and then iterates through that array<br />
to find all of the h2 elements. For each h2, we create a new anchor element that contains an img element (our little<br />
expand/collapse icon), and then we apply some behavior to that anchor. By using an anchor element instead of a span or a<br />
div, we make sure that the expand/collapse functionality is keyboard accessible. anchor elements are focusable via the keyboard<br />
and will receive a click event when the user activates them by pressing the Enter key.<br />
We’re capturing two events on the anchor tag: a mousedown and a click. The mousedown listener is required to counteract<br />
the mousedown that we’ll use for dragging and dropping the content module. Essentially, we want to listen for clicks on the<br />
anchor, but whenever someone clicks a mouse button, it’s also preceded by a mousedown. Because the anchor is inside the<br />
h2, that will trigger the h2’s mousedown event, so we need to cancel the h2’s mousedown event when the anchor’s mousedown<br />
event fires. This is done via mousedownExpandCollapse():<br />
function mousedownExpandCollapse(event)<br />
{<br />
if (typeof event == "undefined")<br />
{<br />
event = window.event;<br />
}<br />
chapter 9 Creating Dynamic Interfaces Using JavaScript<br />
227