views:

509

answers:

2

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?

+2  A: 

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>
cletus
@Cletus - You gave the same link that he already had in his question (2nd link).
klabranche
Yeah, I'd just prefer it if this were packaged as some kind of plugin (copying and pasting code makes me feel dirty).
Horace Loeb
Woops, missed that.
cletus
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?
Horace Loeb
+1  A: 

There's nothing wrong with copying and pasting snippets of code, that's how most people start out and you will keep doing it until you get so familiar with the snippets that you paste that you'll start modifying bits and portions or even starting from scratch by yourself.

For that particular piece of code, I don't really see anything wrong with copying it other than not relying on inline event handlers and unobtrusively adding the 'mousedown' with jQuery.

meder