13.02.2013 Views

WEB STANDARDS CREATIVITY

WEB STANDARDS CREATIVITY

WEB STANDARDS CREATIVITY

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Reorganizing modules<br />

Expanding/collapsing is the easy part. What really puts a user in control is being able to dictate the layout of the modules<br />

themselves. We’re going to allow users to grab a module by its title bar and drag it around—to move it up and down in its<br />

container position, or swap it over to the other module area. Because the reorganization behavior is entirely separate from<br />

the expand/collapse behavior, we can include it in a different file, modular.js, for easy maintenance.<br />

Drag-and-drop event listeners<br />

The first step in setting up our new behavior is to create the event listeners for the drag-and-drop actions:<br />

addLoadListener(initModular);<br />

function initModular()<br />

{<br />

var modules = [document.getElementById("modules1"), document.getElementById("modules2")];<br />

for (var i = 0; i < modules.length; i++)<br />

{<br />

var h2s = modules[i].getElementsByTagName("h2");<br />

for (var j = 0; j < h2s.length; j++)<br />

{<br />

addClass(h2s[j].parentNode, "moduleDraggable");<br />

attachEventListener(h2s[j], "mousedown", mousedownH2, false);<br />

}<br />

}<br />

return true;<br />

};<br />

We add another page load listener using addLoadListener(), but this time it’s calling initModular(), which, much like<br />

initExpandCollapse(), iterates through the module areas, finding each of the h2 elements. For each h2, we then add a new<br />

class, moduleDraggable, to its parent div and create a mousedown event listener on the h2. We place this class on the h2’s<br />

parent div so that we can add in some styling tweaks once we know that JavaScript is enabled. We want to give the users a<br />

hint that the module is movable (otherwise, they might not be aware of this fact), so we use this CSS rule in main.css:<br />

.moduleDraggable h2<br />

{<br />

cursor: move;<br />

}<br />

This changes the cursor to a move cursor when the user hovers her<br />

mouse over a draggable h2 element, as shown in Figure 9-12.<br />

The function called by the mousedown listener on the h2 does a lot of<br />

the work for the drag-and-drop behavior of the modules, by collecting<br />

information and setting up variables:<br />

function mousedownH2(event)<br />

{<br />

if (typeof event == "undefined")<br />

{<br />

Figure 9-12. The mouse cursor changes appearance<br />

when it is hovered over a module’s title bar.<br />

chapter 9 Creating Dynamic Interfaces Using JavaScript<br />

231

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!