Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected text on the page (not in a textarea) with jQuery

This plugin lets you grab text the user has selected in a textarea, and this site has non-jQuery-based instructions for grabbing text the user has selected outside of a text area.

I'm wondering whether the functionality of the latter is available in any jQuery plugin.

Edit: Also, is it possible to get the starting and ending indexes of the selection? I.e., where the selection starts and ends within the containing element?

like image 881
Tom Lehman Avatar asked Aug 23 '09 04:08

Tom Lehman


1 Answers

The reason it's hard to find a plug-in for this isn't that it isn't very "jQuery"ish. By that I mean that jQuery plugins normally operate on jQuery objects and the selection has nothing to do with any elements.

Edit: I missed the fact you posted this link in your question but I'll leave it below for completeness since my version is formatted better (but otherwise identical). :)

<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;
}
</script>
<input type="button" value="Get selection" onmousedown="getSelText()"> 
<form name=aform >
<textarea name="selectedtext" rows="5" cols="20"></textarea>
</form>
like image 135
cletus Avatar answered Sep 20 '22 16:09

cletus