0

Is it possible to select some text within a DIV and right after selection (ie. right after releasing the mouse button) a SPAN appears next to the selected text. I prefer not to use jQuery - just Javascript + CSS if possible.

PS. Ideally it should be possible to select multiple times within the same DIV and the span should only appear on the latest selection (and disappear from the previous selection).

BEFORE SELECTION

<div>Some text to select</div>

AFTER SELECTION

<div>Some text to select <span>[selected!]</span></div>
  • 1
    Hey, you might find some of the stuff in this thread helpful: http://stackoverflow.com/questions/4712310/javascript-how-to-detect-if-a-word-is-highlighted – steakpi May 11 '14 at 22:35
  • Thanks - it may be close to what I need (I hope ;). –  May 11 '14 at 22:38

1 Answers1

0

Using the code from the answered question HERE, I managed to get a solution for you.

HTML:

Some test text for you to select

Javascript:

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

function doSomethingWithSelectedText() {
    var selectedText = getSelectedText();
    if (selectedText) {
        document.getElementById('selectedSpan').innerHTML = selectedText;
    }
}

document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;

HERE IS AN EXAMPLE

Community
  • 1
  • 1
Fizzix
  • 23,679
  • 38
  • 110
  • 176