Creating a Selection (^) ❘ 477
container.innerHTML = 'Here is some sample text for selection';
var range = document.createRange();
range.setStart(container.firstChild, 5 );
range.setEnd(container.firstChild, 17 );
setSelectionRange(range);
}
);
First, you obtain the editable element and place in a variable for ease of use:
var container = document.getElementById('container');
To maintain the simplicity of this example, the handler sets the contents of the editable element
before creating the selection. Although it is fairly easy to select edited and formatted content, it can
become tedious quickly.
container.innerHTML = 'Here is some sample text for selection';
Next, you create a Range object, which corresponds to a selection range.
var range = document.createRange();
You set the bounds of the Range object. In this example, you set the contents of the element; there-
fore, you know the values that would typically be determined or calculated. The start of the Range
is set to the sixth character of the text, and the end is set to the eighteenth character as the offsets
are zero-based.
range.setStart(container.firstChild, 5 );
range.setEnd(container.firstChild, 17 );
Now that you have a Range object with its bounds set, you can call your fi rst helper function for
selection ranges:
setSelectionRange(range);
The setSelectionRange function was added as a utility method to assist with this section of the
chapter and the “Restoring a Selection” section:
function setSelectionRange(range)
{
if (range && window.getSelection)
{
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
As is good practice, you start with some sanity checks. Ensure that a range was provided and that
the browser supports the modern window.getSelection method:
if (range && window.getSelection)
http://www.it-ebooks.info
elliott
(Elliott)
#1