spacer
Yehuda Shiran October 24, 2001
Manipulating a Selection
Tips: October 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Google Going Native With Chrome
Mozilla Fixes Firefox Flaws as 3.5 Release Nears
Microsoft and Novell Still Bosom Buddies

The selection object has three methods:

MethodDescription
"clear()"Clears the contents of the current selection.
"empty()"Deselects the current selection.
"createRange()"Creates a TextRange object for the selection.

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 (not clear()), because an event handler must be assigned a function reference (as opposed to a function call). Note that this script does not work on Navigator 4.0x because it takes advantage of the selection object.

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.

The createRange() method is very simple. It returns a TextRange object for the current selection. Here's an example:

var range = document.selection.createRange();
Handling the object and extracting its data is another story.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
XML and PHP Simplified · Creating a ASP.NET Contact Form · Data Filtering with PHP
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Intel to Host Live Nehalem Q&A · 12 Tips to Troubleshoot Network File-Sharing · 10 Tips for Selling on Kijiji