AJAX - The Complete Reference

(avery) #1

362 Part II: Developing an Ajax Library^


When we are in edit , look for this special inedit- stemmed class and set it to the class
name following the dash. Of course, if you want an “out edit” class, it should just be set as
normal.

<div class="editable doubleclick redborder inedit-blueborder">I start with a red
border. Double click me to edit and then I will have a blue border.</div>

Once the styles have been indicated and the page set up, the user will eventually
interact with editable items and trigger the edit() function that has been associated with
the class named tags. This function first checks to make sure the region is not already being
edited. If it is, the function simply returns. If not, a form field is created to perform the
editing within, any editing style is defined, the form field is populated with the content to
edit and then finally it is inserted into the document. In this version, the cursor position is
also defined, and focus is set to the field to improve usability. You should note at the end of
the edit() function, the association of the onblur event with the save() function. This
function will later be used to invoke a call to the server using Ajax to save the content and
put the data back to normal.

function edit(elm)
{
/* check to see if we are already editing */
if (elm.firstChild.tagName && elm.firstChild.tagName.toUpperCase() ==
"INPUT")
return;
/* create edit field */
var input = document.createElement("input");
input.type = "text";
input.value = elm.innerHTML;
input.size = elm.innerHTML.length;
/* apply special editing style */
var editstyles = elm.className.match(/inedit-(\w+)/);
if (editstyles)
input.className = RegExp.$1;
/* 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();
}
input.focus();

/* set save trigger callback */
input.onblur = function(){save(elm, input);};
}
Free download pdf