domagojk
domagojk

Reputation: 1060

Get selected text outside textbox with jquery

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.

Upvotes: 2

Views: 1901

Answers (2)

Tim Down
Tim Down

Reputation: 324567

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() {
    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);
    }
}

Upvotes: 4

Alberto Santini
Alberto Santini

Reputation: 6564

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;
}

Upvotes: 1

Related Questions