Get selected text on a page (not in a text box) using jQuery

This plugin allows you to capture the text that the user selected in the text field, and this site contains instructions that do not contain jQuery to capture the text that the user selected outside the text area.

I am wondering if the functionality of the latter is available in any jQuery plugin.

Edit: Can I also get start and end selection indices? Ie, where does the selection begin and end inside the containing element?

+6
jquery selection
source share
2 answers

The reason it is difficult to find a plugin for this is not because it is not a very "jQuery" ish. By this I mean that jQuery plugins usually work with jQuery objects, and the selection has nothing to do with any elements.

Edit: I missed the fact that you posted this link in your question, but I will leave it below for completeness, as 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> 
+6
source share

There is nothing wrong with copying and pasting code snippets that, as most people begin to work, and you will continue to do so until you know which snippets you are inserting, you will begin to change bits and parts, or even start with a scratch yourself.

For this part of the code, I really don't see anything wrong with copying, except that I don't rely on the built-in event handlers and unobtrusively add "mousedown" with jQuery.

+3
source share

All Articles