Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Getting the text the user has selected is relatively simple. There's no benefit to be gained by involving jQuery since you need nothing other than the <code>window</code> and <code>document</code> objects.</p> <pre><code>function getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection &amp;&amp; document.selection.type != "Control") { text = document.selection.createRange().text; } return text; } </code></pre> <p>If you're interested in an implementation that will also deal with selections in <code>&lt;textarea&gt;</code> and texty <code>&lt;input&gt;</code> elements, you could use the following. Since it's now 2016 I'm omitting the code required for IE &lt;= 8 support but I've posted stuff for that in many places on SO.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function getSelectionText() { var text = ""; var activeEl = document.activeElement; var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null; if ( (activeElTagName == "textarea") || (activeElTagName == "input" &amp;&amp; /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &amp;&amp; (typeof activeEl.selectionStart == "number") ) { text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd); } else if (window.getSelection) { text = window.getSelection().toString(); } return text; } document.onmouseup = document.onkeyup = document.onselectionchange = function() { document.getElementById("sel").value = getSelectionText(); };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>Selection: &lt;br&gt; &lt;textarea id="sel" rows="3" cols="50"&gt;&lt;/textarea&gt; &lt;p&gt;Please select some text.&lt;/p&gt; &lt;input value="Some text in a text input"&gt; &lt;br&gt; &lt;input type="search" value="Some text in a search input"&gt; &lt;br&gt; &lt;input type="tel" value="4872349749823"&gt; &lt;br&gt; &lt;textarea&gt;Some text in a textarea&lt;/textarea&gt;</code></pre> </div> </div> </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload