Everything Can be a Link with Mozilla's window.getSelection() Method and the W3C DOM Range API

by Brian Donovan
7/09/02 (ahoy.js updated 5/06/03)

Download Ahoy (GPL) : 19 Kb zipfile, 49 Kb .js file (prune out copious comments to get the file size down)
Comments, bugs, suggestions

This page is a demo

(If you're using Mozilla or a Mozilla-based browser, Alt+clicking and dragging across a text fragment will trigger Ahoy and furnish you with an Ahoy link to your selection.)

Note : An extended discussion of the mechanics of Ahoy is available in my tutorial at IBM developerWorks (link, registration required), published October 2002. A draft of the article is also available here. Please feel free to download and use Ahoy (available under the GPL). Simply link the script into your documents using an empty <script> element with its src attribute value pointing to ahoy.js.

In coding Ahoy, my goal was to enable user-driven text selection and linking throughout web pages for visitors piloting Mozilla, Netscape 6.x, Netscape 7.x, and other Mozilla-based browsers through JavaScript, the W3C DOM, and Mozilla's getSelection() DOM extension. I've dubbed the system that I created and implemented along these lines at my own site "Ahoy", in-keeping with the nautical theme underlying so much of the web lexicon (navigator for web browser, anchor elements for linking, etc.).

Some Considerations

The offsets provided by Mozilla's select object (anchorOffset and focusOffset) seem to ignore multiple spaces within selections, treating them, for counting purposes, as single chars, but the toString() method of the Range object, as implemented in Mozilla, respects multiple spaces in the source, causing the length of the text child nodes within the Ahoy anchors created from text selections containing multiple spaces to be shorter by the the sum of the number of consecutive multiple spaces minus one. This is something that can be dealt with, but I haven't tackled it yet.

Because Ahoy references a piece of text by its offset and length within its text node, the index of the selection's text node within the childNodes collection of its parent, and either the index of the text node's parent element node within the collection of element nodes returned by getElementsByTagName() or the ID attribute value of the text node's parent node, existing Ahoy links to documents can be broken by editing.

Updates

May 06 2003 1.1 release : In response to a change in Mozilla's behavior w/respect to the target property of event objects fired by mousedown and mouseup events, Ahoy now takes advantage of the anchorNode and focusNode properties of Mozilla's native Selection objects.