Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a solution that will work without adding tons of spans to the document (works on Webkit and Mozilla and IE9+):</p> <p><a href="http://jsfiddle.net/Vap7C/15/" rel="noreferrer">http://jsfiddle.net/Vap7C/15/</a></p> <pre><code>&lt;p class="clickable"&gt;some words&lt;/p&gt; $(".clickable").click(function(e) { s = window.getSelection(); var range = s.getRangeAt(0); var node = s.anchorNode; while (range.toString().indexOf(' ') != 0) { range.setStart(node, (range.startOffset - 1)); } range.setStart(node, range.startOffset + 1); do { range.setEnd(node, range.endOffset + 1); } while (range.toString().indexOf(' ') == -1 &amp;&amp; range.toString().trim() != '' &amp;&amp; range.endOffset &lt; node.length); var str = range.toString().trim(); alert(str); });​ </code></pre> <p>in IE8, it has problems because of getSelection. This link ( <a href="https://stackoverflow.com/questions/3076052/is-there-a-cross-browser-solution-for-getselection">Is there a cross-browser solution for getSelection()?</a> ) may help with those issues. I haven't tested on Opera.</p> <p>I used <a href="http://jsfiddle.net/Vap7C/1/" rel="noreferrer">http://jsfiddle.net/Vap7C/1/</a> from a similar question as a starting point. It used the <a href="https://developer.mozilla.org/en/DOM/Selection" rel="noreferrer">Selection.modify</a> function:</p> <pre><code>s.modify('extend','forward','word'); s.modify('extend','backward','word'); </code></pre> <p>Unfortunately they don't always get the whole word. As a workaround, I got the <a href="https://developer.mozilla.org/en/DOM/range" rel="noreferrer">Range</a> for the selection and added two loops to find the word boundaries. The first one keeps adding characters to the word until it reaches a space. the second loop goes to the end of the word until it reaches a space. </p> <p>This will also grab any punctuation at the end of the word, so make sure you trim that out if you need to.</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. 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