Ad

Why GetSelection() Always Returns Nothing?

- 1 answer

$("body").on('click', 'button', function(e) {
  var selection =  window.getSelection().toString();
  alert(selection);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="txtarea">this is a test</textarea>
<button>click</button>

In the above fiddle, I expect to it return selected-text (in the textarea) when I click on that button, but it always returns nothing. How can I fix it?

Note: This doesn't work either:

var selection = window.getElementById("txtarea").getSelection().toString();

Ad

Answer

The click event happens when the mouse button is pressed, and then released, and at that time the selection is lost.

You have to use the mousedown event instead, which happens just when the mouse button is pressed, before the selection is lost

function getSelection(elem) {
    var selectedText;

    if (document.selection != undefined) { // IE
        elem.focus();
        var sel = document.selection.createRange();
        selectedText = sel.text;
    } else if (elem.selectionStart != undefined) { // Firefox
        var startPos = elem.selectionStart;
        var endPos   = elem.selectionEnd;
        selectedText = elem.value.substring(startPos, endPos)
    }
    return selectedText;
}

$(document).on('mousedown', 'button', function(e) {
  var selection =  getSelection( $('#txtarea').get(0) );
  alert(selection);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="txtarea">this is a test</textarea>
<button>click</button>

Ad
source: stackoverflow.com
Ad