1

Is there a javascript function that will allow me to capture the text that is currently highlighted with the cursor and store it in a variable? I've been trying document.selection.createRange().text but this hasn't been working. Are there any possible alternatives? Here's the code:

function moremagic(){
var output = document.selection.createRange();
alert("I Work!");}

When I run the function, it doesn't make it to the write statement so I know something is wrong.

3 Answers3

1

Ungraciously stolen from another question:

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection();
    }
    else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}

Use this in a "onClick" function or whatever and it will return the selected text in almost any browser.

Community
  • 1
  • 1
Organiccat
  • 5,555
  • 17
  • 54
  • 98
  • `window.getSelection()` will return a `Selection` object, not a string. – Tim Down Jul 20 '10 at 09:07
  • The way I read it, it's just for checking the return value for a browser check. One works in "all" browsers, the other works in IE ;) – Organiccat Jul 21 '10 at 00:22
  • I think you misunderstood. You're correct that it's checking for the existence of objects/functions before using them. The issue is that this function will return a `Selection` object in non-IE browsers and a string in IE. You need to call `toString()` on the `Selection` before returning. – Tim Down Jul 21 '10 at 08:27
0

Yep, you want window.getSelection.

oldestlivingboy
  • 2,594
  • 1
  • 18
  • 15
0
function getSelectedText() {
    if (window.getSelection) {
        return "" + window.getSelection();
    } else if (document.selection && document.selection.type == "Text") {
        return document.selection.createRange().text;
    }
    return "";
}
Tim Down
  • 292,637
  • 67
  • 429
  • 506