0

I am making a web page and i want to get the highlighted text. Problem is,i want to do something when a user highlights text anywhere within the page.

I have this

$("body").select( function (e) { 
        alert("You selected: "+window.getSelection());
    });

here https://jsfiddle.net/xn9mnmy1/

but it does not seem to work.

What could i be doing wrong?.

ac dc
  • 1
  • 1
    Possible duplicate of [Can I get highlighted text with JQuery?](http://stackoverflow.com/questions/17227070/can-i-get-highlighted-text-with-jquery) – Vucko May 05 '16 at 21:48
  • 1
    There is no `select` event. Try `mouseup`: https://jsfiddle.net/xn9mnmy1/1/ – Rory McCrossan May 05 '16 at 21:49

3 Answers3

0
$('body').on('click', function(){

    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }

    alert(text);       
});

Source: Can I get highlighted text with JQuery?

Community
  • 1
  • 1
Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29
0

Using the .click() method you can send the selected text as an alert to the user.

You have to make sure if the selected text string is not empty before calling alert() or you will get an alert every time you click anywhere.

$('body').click(readText);

function readText(){
    var text = window.getSelection().toString();
    if(text.length > 0){
            alert("You selected:\n" + text);
        }  
}

See: https://jsfiddle.net/r24b0dpv/

spencer.sm
  • 19,173
  • 10
  • 77
  • 88
-1

Straight from the documentation:

This event is limited to <input type="text"> fields and <textarea> boxes.

Paul Abbott
  • 7,065
  • 3
  • 27
  • 45