Web Development with jQuery®

(Elliott) #1

(^478) ❘ CHAPTER 22 CREATING A SIMPLE WYSIWYG EDITOR
You then obtain the current Selection object.
var sel = window.getSelection();
The Selection object may contain zero to many selection ranges. In general, it contains zero until the
page is clicked and one thereafter. You start by removing any existing selection ranges:
sel.removeAllRanges();
Finally, you add the programmatically created range to the Selection object, which fi nally selects the
text “is some samp” within the editable element.


Storing a Selection


Within the previous example code, the markup was updated to add a button to the toolbar for
storing the current position of a selection range:

<button id='btnStoreSelection'>Store Selection</button>

You updated the JavaScript to add a click event handler for this button. The handler performs the
incredibly simple task of setting a window-level variable to store information about the currently
selected content:

$('button#btnStoreSelection').click(
function()
{
window.selectedRange = getSelectionRange();
}
);

Notice that you used your second helper function:


function getSelectionRange()
{
if (window.getSelection)
{
var sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount)
{
return sel.getRangeAt( 0 );
}
else // Safari
{
var range = document.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
return range;
}
}
return null;
}

http://www.it-ebooks.info

Free download pdf