AJAX - The Complete Reference

(avery) #1

PART II


Chapter 8: User Interface Design for Ajax 365


Click-to-Edit List


Now we experiment with the click-to-edit concept within the simple to-do list example. As
before, a class name is used to indicate editable and, when the document loads, the library
method getElementsBySelector() is used to bind the triggered functions to the elements
of interest. The following function is called on page load and associates a call to edit()
with all the list items in editable lists.

window.onload = function ()
{
var listItems = AjaxTCR.util.DOM.getElementsBySelector("ol.editable li");
for (var j = 0; j < listItems.length; j++)
listItems[j].ondblclick = function(e){edit(this);};
};

Notice that double-clicking is used here to trigger the edit. You might wonder why.
Consider what would happen if you used single-clicking and blurring with items very close
together. In a situation where you blur a field to save it, you will then very likely start editing
the field next to it. By setting the action trigger to double-click, we ensure the user is actually
interested in editing something.
When the user invokes the editing, the code is pretty much the same as the code used in
the introduction to the interface idiom, except for the fact that the original value is saved in
the edited item for later use.

function edit(elm)
{
/* check to see if we are already editing */
if (elm.firstChild.tagName && elm.firstChild.tagName.toUpperCase() ==
"INPUT")
return;
/* save original content */
var orig = elm.innerHTML;
/* create edit field */
var input = document.createElement("input");
input.type = "text";
input.value = elm.innerHTML;
input.size = 20;
/* convert content to editable */
elm.innerHTML = '';
elm.appendChild(input);
/* position cursor and focus */
if (input.selectionStart)
input.selectionStart = input.selectionEnd = 0;
else
{
var range = input.createTextRange();
range.move("character", 0);
range.select();
}
Free download pdf