Web Development with jQuery®

(Elliott) #1

Restoring a Selection (^) ❘ 479
After dispensing with the window.getSelection sanity check (feature detection), you obtain the cur-
rent Selection object as with the other helper function. This time, you access additional information
about the object. In most cases, the Selection object supports the getRangeAt method; you check for
support as well as the existence of selection ranges. If the tests pass, return the fi rst Range object
within the Selection object:
if (sel.getRangeAt && sel.rangeCount)
{
return sel.getRangeAt( 0 );
}
If the logic tests fail (as is the case with Safari, which does not support getRangeAt), use familiar
code to create a Range object, this time using bound information from the Selection object to spec-
ify the start and end containers and offsets:
else // Safari
{
var range = document.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
return range;
}
Finally, if basic feature detection indicated a lack of support for the modern Selection object, simply
return null and move on. This is one of those instances in which it might be a good idea to alert the
user that a better experience can be obtained with a newer browser.
return null;
Unless you hit the last case in which the Selection object was not available, you should have stored
enough information about the selected content for later use.
RESTORING A SELECTION
The last button added in the previous code example’s markup enabled the restoration of a previous
selection within the editable element.



You included one fi nal JavaScript event handler for the click of this button. First, you test for the
existence of the previously stored selection. If it does exist, pass it to the previously discussed helper
function, which deselects any current selections and restores the saved selection.
$('button#btnRestoreSelection').click(
function()
{
if (window.selectedRange)
{
setSelectionRange(window.selectedRange);
}
}
);
[http://www.it-ebooks.info](http://www.it-ebooks.info)
Free download pdf