0

http://api.jquery.com/select/ mentions that $().select()

"The select event is sent to an element when the user makes a text selection inside it. This event is limited to <input type="text"> fields and <textarea> boxes."

I am trying to detect text selection in <div>.

What's the best way to provide the equilvalent $().select()?

Thanks in advance for your help.

alex
  • 438,662
  • 188
  • 837
  • 957
pion
  • 3,483
  • 5
  • 25
  • 40

2 Answers2

2

I use the following code in my pages:

if (document.selection)
 {
     text = document.selection.createRange().text;
 }

else if (document.getSelection)
 {
     text = document.getSelection();
 }

else if (window.getSelection)
 {
     text = window.getSelection();
 }
else return;

It has some problems with newer versions of IE but other than that it's pretty good.

esqew
  • 34,625
  • 25
  • 85
  • 121
2

A similar Q&A is posted here. You could use that function to get selected text in a div bound to the mouseup javascript event.

E.g.

$('#div').mouseup(function() {
  alert(getSelectedText());
});

// Get user selection text on page
function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection();
    }
    else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}
Community
  • 1
  • 1
Tak
  • 10,344
  • 5
  • 26
  • 47