/ Uncategorized

Stringify JavaScript

This code reads selected text after a user releases the mouse button. I came up with this technique after I read a questions at Stack Overflow. I never actually used it on any web projects, but it might come in handy at a later time.

IE uses the native createRange(); method and Webkit can use the getSelection(); method of the window or document object.


document.onmouseup = function() {

   var txt = ' ';

   // Webkit
   if (window.getSelection) {
      txt = window.getSelection();

   // Webkit Alternative
   else if (document.getSelection) {
      txt = document.getSelection();

   // IE
   else if (document.selection) {
      txt = document.selection.createRange().text;

   // if no selection then break here
   else return;

   document.someForm.selectedtext.value = txt;


<form name="someForm">
	<textarea name="selectedtext" rows="5" cols="20"></textarea>

View an example of this technique here: TextSelect Example

Stringify JavaScript
Share this