-1

asdf

Given this div, if a user were to select the word asdf with their cursor, the the character count would be 4.

In JavaScript, how can you determine what the user has selected with their cursor; more specifically, text.

jQuery library preferred.

I've tried:

var text = document.getSelection().toString();
var length = document.getSelection().toString().length;
if (text) {
    alert(text);
}
if (length) {
    alert(length);
}

http://jsfiddle.net/fxjgW/

O P
  • 2,327
  • 10
  • 40
  • 73

1 Answers1

3

Seeing your updated question I see the problem is that you're not triggering the text selection, as far as I know there is no DOM event for text selection, but you can set it for mouseup, like this:

$(document.body).on('mouseup', function(){
    var text = document.getSelection().toString();
    var length = document.getSelection().toString().length;
    if (text) {
        alert(text);
    }
    if (length) {
        alert(length);
    }
});

Update jsfiddle

DarkAjax
  • 15,955
  • 11
  • 53
  • 65
  • I gave that a try, but it didn't seem to work. I've updated my post with what I've tried. – O P Apr 26 '13 at 16:21
  • This works great except for the case where the user drags their mouse outside the bounds of the jsfiddle iframe and the mouseup is never caught. Not sure if the OP has some similar situation. – LouD Apr 26 '13 at 16:48