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:

19 May : Heating Oil Thefts - Stay Alert!
19 May : Pro Blaze Overshoes pass the test
15 May : Get a CentOS Server Web-Ready
13 May : Keeping your iPhone secure
06 May : Nero, Claudius and a rather dead mouse
19 May : Domestic Heating Oil Prices: Know the Market!
19 May : Sports Gear: Under Test
15 May : Rackspace Cloud Hosting
13 May : iPhone 4
06 May : Cats
19 Mar : Time Trial Results
25 Nov : Piano for the Amateur
14 Nov : Measure
02 Nov : Book Reviews
12 Oct : Simple Programming Exercises

Popular Searches: