65.9K
CodeProject is changing. Read more.
Home

JavaScript code to get selected text

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (2 votes)

Nov 30, 2011

CPOL
viewsIcon

35472

We know getting the selected text from a HTML page is a basic thing. But I think the code is not widely available.

We know getting the selected text from an HTML page is a basic thing. But I think the code is not widely available. The JavaScript code below fetches the value anywhere in a page including textarea, input and text fields of the forms.

function GetSelectedText()
{
  var selectedText=(
        window.getSelection
        ?
            window.getSelection()
        :
            document.getSelection
            ?
                document.getSelection()
            :
                document.selection.createRange().text
     );
 if(!selectedText || selectedText=="")
 {
    if(document.activeElement.selectionStart)
    {
     selectedText = document.activeElement.value.substring(
          document.activeElement.selectionStart
          . document.activeElement.selectionEnd);
    }
 }
 return selectedText;
}

Here are the bonus bookmarklets for the dictionaries for English and Tamil.

//English Dictionary

javascript:var%20newfunc=function%20a(){q=window.getSelection?
	window.getSelection():document.getSelection?document.getSelection():
	document.selection.createRange().text;if(!q||q=="")
	{if(document.activeElement.selectionStart)
	{q= document.activeElement.value.substring
	(document.activeElement.selectionStart,document.activeElement.selectionEnd)}}
	if(!q||q=="")q=prompt("Enter%20term:");if(q!=null)window.open
	("http://www.wordreference.com/definition/"+q)}() 
//English to Tamil

javascript:var%20newfunc=function%20a(){q=window.getSelection?window.
	getSelection():document.getSelection?document.getSelection():
	document.selection.createRange().text;if(!q||q=="")
	{if(document.activeElement.selectionStart)
	{q= document.activeElement.value.substring
	(document.activeElement.selectionStart,document.activeElement.selectionEnd)}}
	if(!q||q=="")q=prompt("Enter%20word:");if(q!=null)window.open
	('http://www.eudict.com/index.php?lang=engtam&word='+q)}()
//Tamil to English

javascript:var%20newfunc=function%20a(){q=window.getSelection?
	window.getSelection():document.getSelection?document.getSelection():
	document.selection.createRange().text;if(!q||q=="")
	{if(document.activeElement.selectionStart)
	{q= document.activeElement.value.substring
	(document.activeElement.selectionStart,document.activeElement.selectionEnd)}}
	if(!q||q=="")q=prompt('Enter%20word%20in%20Tamil:');
	if(q!=null)window.open('http://www.eudict.com/index.php?lang=tameng&word='+q)}()