Capturing selected text in Javascript

By 28 Nov 2011 | Comment

Here's how to immediately capture the text on your web page that a visitor has highlighted with their mouse. Select some text on this page, and it should appear in the text box below. Clicking on links carries on working just fine, but you can double-click on a word and that will get captured.


The HTML Source:

<script language=javascript>
function getSelText()
{
    var txt = '';
     if (window.getSelection)
    {
        txt = window.getSelection();
             }
    else if (document.getSelection)
    {
        txt = document.getSelection();
            }
    else if (document.selection)
    {
        txt = document.selection.createRange().text;
            }
    else return;
    document.aform.selectedtext.value =  txt;
}
$(function(){
 $('body').mouseup(function(){
  getSelText();
 });
});
</script>
<form name=aform >
<textarea name="selectedtext" rows="10" cols="50"></textarea>
</form>

getSelText source: codetoad.com


Comments

It's quiet in here...Add your comment

Recent Updates:

18 Feb : Barclays Pingit enables mobile-to-mobile payments
11 Feb : Solar PV Readings for Cherwell, south-facing
11 Feb : Feed-in Tariffs explained
09 Feb : Solar PV Readings for Cherwell, east-facing
04 Feb : Dodgy connection? Don't just blame your ISP
18 Feb : Finance
11 Feb : My Solar PV
11 Feb : Solar PV Electricity
04 Feb : About Us: Julii & John Swindells
04 Feb : Internet Access
25 Nov : Piano for the Amateur
14 Nov : Measure
02 Nov : Book Reviews
12 Oct : Simple Programming Exercises
11 Oct : Model Railways

Popular Searches: