Capturing selected text in Javascript

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 src="/javascript/jquery.min.js"></script>
<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