views:

49

answers:

2

Is it possible to retrive selected text outside textbox? I had seen solutions to get text from input forms and textareas, similar to this: http://laboratorium.0xab.cd/jquery/fieldselection/0.2.3-test/test.html but can this aplied on HTML text (inside div element)?

For example, I want user to be able to bold selected text which is not in textarea.

A: 

In order to get the selected text in any part of the document you can use window.getSelection, document.getSelection or document.selection. You should try each of the above if you want to achieve cross-compatibility, like:

if (window.getSelection) {
  window.getSelection();
} else if (document.getSelection) {
  document.getSelection();
} else if (document.selection) {
  document.selection.createRange().text;
}
Alberto
+3  A: 

Yes, it's possible. IE and other browsers have rather different mechanisms for dealing with selections. If you simply want the selected text, the following will do it:

function getSelectedText() {
    var text = "";
    if (window.getSelection) {
        text = "" + window.getSelection();
    } else if (document.selection && document.selection.createRange &&
            document.selection.type == "Text") {
        text = document.selection.createRange().text;
    }
    return text;
}

To address your specific question, you can use document.execCommand("bold", null, false); to make the current selection bold. In non-IE browsers you have to temporarily put the document into edit mode first though:

function toggleSelectionBold(colour) {
    var range, sel;
    if (window.getSelection) {
        // Non-IE case
        sel = window.getSelection();
        if (sel.getRangeAt) {
            range = sel.getRangeAt(0);
        }
        document.designMode = "on";
        if (range) {
            sel.removeAllRanges();
            sel.addRange(range);
        }
        document.execCommand("bold", null, false);
        document.designMode = "off";
    } else if (document.selection && document.selection.createRange &&
            document.selection.type != "None") {
        // IE case
        range = document.selection.createRange();
        range.execCommand("bold", null, false);
    }
}
Tim Down
Thanks, it worked... But just one more thing... I also want to replace selected text and for IE I menaged to do that with range.text="someting", but I don't know how to do that for other browsers?
domagoj412
Might be better as a separate question.
Tim Down
http://stackoverflow.com/questions/3702788/replacing-selected-html-text-in-jquery
domagoj412