Page Rearrangement - Ajax Patterns

Page Rearrangement

From Ajax Patterns

Evidence: 3/3

Tags: Add Adjust Change Delete DOM Move Rearrange Restructure Remove


Contents

In A Blink

Diagram: Portlets/Portal


Goal Story

Doc is looking at an X-Ray image in an online diagnostics system. He mouse-clicks on the bottom-right region to reveal the time and date of the X-Ray. He then decides to annotate the image, so double-clicks on a critical point to pop up an editable "sticky note".


Problem

How can you dynamically restructure the page?


Forces

  • As the user's task and context changes, Ajax applications need to present different information.
  • Changes to page structure should be as smooth as possible.
  • Refreshing the page breaks continuity and also clears Javascript state.
  • Refreshing the page only allows for a discrete transition from one appearance to another - it's not possible to gradually fade or move an item.


Solution

Add, remove, move, and overlay elements by manipulating the DOM. The DOM is a hierarchical structure that defines how elements relate to one another. By adjusting the DOM structure, you can adjust where elements appear on the page. There are also critical CSS styles that affect page structure - you can affect these by manipulating DOM elements' style attributes.

Note: An online demo illustrates most of the code concepts throughout this Solution and the code snippets loosely follow from the demo.

Adding is normally achieved by introducing a new element as a child of an existing container element, such as body or div. For example, you can create a new div element and add it to a parent div.

 var message = document.createElement("span");
 $("container").appendChild(message);

Another way to insert an element is to append to the innerHTML property of the container element.

 $("container").innerHTML += "";

The opposite action is removing. By removing an element from the DOM, you take it off the display.

 $("container").removeChild($("message"));

As a variant of adding and removing, you can keep an element on the page, but toggle its visibility using CSS. There are two alternatives here. The visibility and display. The former will always preserve layout while the latter will cause the element to squeeze in and out when it's shown or hidden. So with visibility, it's like the element's still there but wearing invisible paint; whereas. This makes layout easy, because everything stays where it is, but it can be ugly to have a big patch of whitespace on the page. With the display style, it's more like the element's shoved into a temporary store to make room for other elements, which adds more layout complexity but is often more appropriate from a visual perspective. For visibility, the style property is switched between visible and hidden.

   $("message").style.visibility = "visible"; // Now you see me
   $("message").style.visibility = "hidden";  // Now you don't

display is actually used for more than just showing and hiding an element - it also defines how an element appears when it is visible. It's beyond the scope of these patterns to cover the options in detail, but the main options are block (the default for div elements) and inline (the default for span) elements. To show and hide using display, you switch its value between none and one of these values.

   $("message").style.display = "block"; // Now you see me, with block layout
   $("message").style.display = "none";  // Now you don't

You can move an element around in a couple of ways. Firstly, you can remove it from one place in the DOM and add it to another.

   container.removeChild(message);
   extraContainer.appendChild(message);

Second, you can adjust CSS properties. The most direct styles are left, right, top, and bottom, which define the co-ordinates of the element in question.

   message.style.top = "150px";
   message.style.left = "50px";

But what is the (0,0) point these co-ordinates are relative to? The precise meaning of these styles is modulated by the positioning element.

  • If static, the co-ordinates have no effect - the element is positioned according to standard CSS layout rules.
  • If relative, the co-ordinates are relative to the position it would normally be positioned under standard CSS layout rules - they suggest how far its displaced.
  • If absolute, the co-ordinates are relative to the top-left of the entire document.
  • If fixed, the co-ordinates are relative to the top-left of the browser viewport (the portion of the browser window that shows the page). Even if you scroll the document, the element will stick right on the same point on the screen as before.

Positioning is set as a standard CSS style.

   message.style.positioning = "150px";

Finally, you can also overlay elements. An HTML document has "2.5" dimensions, which is to say that it has a limited notion of depth in which elements are able to overlap each other. The critical CSS style here is zIndex, which signifies an element's depth. When two elements occupy the same portion of the page, the element which will appear in front is that with the higher zIndex. The zIndex is not a real depth, because all that matters is the relative ordering of zIndex values. Against a zIndex of zero, it makes no difference whether an element's zIndex is 1, 10, or 100. The default value is 0 and a zIndex can take on any positive or negative value.

   message.style.zIndex = -100; // Behind of all elements with default zIndex
   message.style.zIndex = 100;  // In front of all elements with default zIndex


Decisions

Which positioning style to use?

A single application can combine different types of positioning. In most cases, static - the default positioning - suffices. Non-static positioning is most commonly used with more free-floating elements, such as Sprites or elements suitable for Drag-And-Drop. For non-static positioning, relative positioning tends to be the most useful, because it allows you to move the element around within a defined container.

How will you protect against memory leaks?

Continuously adding and removing elements leads to the risk of memory leaks. Javascript is supposed to perform garbage collection, automatically removing variables that are no longer referenced. Some general guidelines:

  • Avoid global variables where possible. Local variables go out of scope, so if a local variable points to a deleted element, the element will disappear. But if a global variable points to such an element, it will stick around.
  • Explicitly nullify references. Where you're sure a variable will no longer need to use the value it references, set the variable to null.
  • Avoid or destroy circular references You can sometimes end up with a circular structure that no-one's using anymore, but sticks in memory because garbage collection isn't smart enough to remove it (it concludes each object is still relevant because at least one reference exists). This can happen, for instance, when an object's event handler refers back to the object (see "Javascript Closures" for more details).
  • Test, test, test It may not be fun, but you need to stress test your application under different browser environments, monitoring memory usage to ensure it's stable.

web monitor


Real-World Examples

Tadalist

Ta-da List (Screencast available) allows users to manage TODO items. Each TODO item is a phrase like "Finish homework" and the user can add, remove, and rearrange items.

Super Maryo World

Super Maryo World is an outright video game, a clone of the classic Super Mario Bros game implemented with standard Ajax technologies. The manipulation of game characters and fixtures illustrates how elements can rapidly be added, removed, and moved around.

Kiko

Kiko is a visual Ajax calendar application. You can add and remove appointments, drag them around to change the time, and stretch them out to increase duration.


Code Examples

Basic Wiki Demo

The Basic Wiki Demo periodically polls for a fresh list of messages to display. Each time the list is retrieved, it removes all existing messages and adds the new list. The containing element is called "messages" and removing all messages runs a loop across each of its children.

 while ($("messages").hasChildNodes()) {
   $("messages").removeChild($("messages").firstChild);
 }

Each message is used to create a new textarea element (among other things), which is then added to a new div, which in turn is added to the messages container.

 for (var i=0; i<wikiMessages.length; i++) {
   var messageArea = document.createElement("textarea");
   ...
   messageDiv = document.createElement("div");
   ...
   messageDiv.appendChild(messageArea);
   ...
   $("messages").appendChild(messageDiv);
   ...
 }


Alternatives


Related Patterns

The Display Morphing pattern addresses an element's appearance; this pattern talks about elements' location, visibility, and "height above the page" (z-index). Together, the two patterns cover any


Visual Metaphor

Page rearrangement is like adding, removing, and rearranging Post-It notes on a whiteboard.