January 17, 2000 - The Selection Object
January 17, 2000|
The Selection Object
Tips: January 2000
Yehuda Shiran, Ph.D.
document.selectionobject which encapsulates a property and several methods that handle selections. The
selectionobject provides information about the text and elements the user has currently highlighted with the mouse. This can be very useful if you want to perform some action based upon what the user has selected.
type property defines the type of selection. This read-only string property can have one of the following values:
|No selection or insertion point.|
|The selection is a text selection.|
|The selection is a control selection.|
The default value is obviously
"None", when there is no selection. Therefore, comparing the value of
"None" on Internet Explorer 4.0 and up is equivalent to comparing the value returned by the
document.getSelection() method with
"" on Navigator 4.0 and up.
selection object has three methods:
|Clears the contents of the current selection.|
|Deselects the current selection.|
|Creates a |
Take a look at the following statement:
document.onmouseup = document.selection.clear;
If you embed this statement in a script, the browser deletes all selections. In other words, when the user selects a portion of the document, the browser immediately removes that portion. If the selection also consists of other non-text elements, they are removed in the same way. The page is rendered according to the new content. Notice that the
clear() method is specified as
clear()), because an event hander must be assigned a function reference (as opposed to a function call). Note that this script does not work on Navigator 4.0 and up because it takes advantage of the
empty() method simply deselects the current selection. A nice, but useless implementation of this method is to create a selection-free page:
document.onmouseup = document.selection.empty;
This statement instructs the browser to deactivate any existing selection. In other words, it un-highlights the selection. Note that the
empty() method also scrolls the window to the top of the page. Therefore, the preceding statement scrolls the window to the top whenever you release the mouse button.
createRange() method is very simple. It returns a
TextRange object for the current selection. Here's an example:
var range = document.selection.createRange();