JSFiddle - React, Tailwind, and code Playground
by timdown
HTML
<script src="http://rangy.googlecode.com/svn/trunk/dev/rangy-core.js"></script>
<script src="http://rangy.googlecode.com/svn/trunk/dev/rangy-textrange.js"></script>
<p>I am living in <b>India</b>. India is a very beautiful country.</p>
<p>Please select something</p>
<p id="info"></p>
JavaScript
document.onmouseup = function() {
var sel = rangy.getSelection();
if (sel.rangeCount > 0) {
var range = sel.getRangeAt(0);
// Expand the range to contain the whole word
range.expand("word");
// Count all the preceding words in the document
var precedingWordCount = 0;
while (range.moveStart("word", -1)) {
precedingWordCount++;
}
// Display results
document.getElementById("info").innerHTML = "Selection starts in word number " + (precedingWordCount + 1);
}
};