log in

Javascript: text selection

Luke Breuer
2010-11-16 20:43 UTC

Javascript can be used to programmatically detect and alter text selection, both of regular rendered text and textareas.
Firefox's text selection abilities can be discovered by starting at the Range object, which is usually obtained via window.getSelection().getRangeAt(0).
Apparently there can be multiple ranges, but I don't see when this would happen. It would probably be good to assert that rangeCount == 1. The plaintext version of the currently selected text can be called via window.getSelection().getRangeAt(0).cloneContents().textContent.
Internet Explorer
IE uses the TextRange object. One obtains it via calling createTextRange() on body, textarea, or input.
Disabling text selection
Assign the following function to be the event handler of an element's onmousedown event. This is useful for drag and drop, as is demonstrated in my drag and drop tutorial.
function OnMouseDown(e)
    // prevent text selection in IE
    document.onselectstart = function () { return false; };
    // prevent text selection (except IE)
    return false;