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
  • 479,566
  • 201
  • 878
  • 984
pion
  • 3,593
  • 6
  • 29
  • 41

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
  • 42,425
  • 27
  • 92
  • 132
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
  • 11,428
  • 5
  • 29
  • 48