15.02.2013 Views

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

286<br />

<strong>JavaScript</strong> <strong>Examples</strong> <strong>Bible</strong>: The Essential Companion to <strong>JavaScript</strong> <strong>Bible</strong><br />

Range.insertNode()<br />

property of the undoBuffer global variable object). After that, the selection is<br />

deleted from the document tree, leaving the selection as a collapsed insertion<br />

point. A copy of that selection in the form of a range object is preserved in the<br />

undoBuffer object so that the undo script knows where to reinsert the original<br />

text. A new text node is created with an uppercase version of the original text, and,<br />

finally, the insertNode() method is invoked to stick the converted text into the<br />

collapsed range.<br />

Undoing this operation works in reverse. Original locations and strings are<br />

copied from the undoBuffer object. After creating the range with the old start and<br />

end points (which represent a collapsed insertion point), the resurrected text (converted<br />

to a text node) is inserted into the collapsed range. For good housekeeping,<br />

the undoBuffer object is restored to its unused form.<br />

Listing 19-5: Inserting a Node into a Range<br />

<br />

<br />

NN Selection Object Replacement<br />

<br />

var undoBuffer = {rng:null, txt:””}<br />

function convertSelection() {<br />

var sel, grossRng, netRng, newText<br />

try {<br />

sel = window.getSelection()<br />

if (!sel.isCollapsed) {<br />

grossRng = sel.getRangeAt(0)<br />

undoBuffer.txt = grossRng.toString()<br />

sel.deleteFromDocument()<br />

netRng = sel.getRangeAt(0)<br />

undoBuffer.rng = netRng<br />

newText = document.createTextNode(undoBuffer.txt.toUpperCase())<br />

netRng.insertNode(newText)<br />

}<br />

}<br />

catch(err) {<br />

alert(“Vital Range object services are not yet implemented in this<br />

browser.”)<br />

}<br />

}<br />

function undoConversion() {<br />

var rng, oldText<br />

if (undoBuffer.rng) {<br />

rng = document.createRange()<br />

rng.setStart(undoBuffer.rng.startParent, undoBuffer.rng.startOffset)<br />

rng.setEnd(undoBuffer.rng.endParent, undoBuffer.rng.endOffset)<br />

oldText = document.createTextNode(undoBuffer.txt)<br />

rng.insertNode(oldText)<br />

undoBuffer.rng = null<br />

undoBuffer.txt = “”<br />

}<br />

}

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

Saved successfully!

Ooh no, something went wrong!