Home:ALL Converter>Index of selected words using Javascript

Index of selected words using Javascript

Ask Time:2012-06-18T03:03:34         Author:Virendra Gupta

Json Formatter

How can I get the index of selected text in HTML using Javascript? For example, in an HTML file, there is paragraph like the following:

I am living in India. India is the very beautiful country.

Now if the user selects India in the first sentence then there should be an alert 5 and if the user selects India of second line then there is an alert 6.

How can I get the index of the word that the user selected?

Author:Virendra Gupta,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/11074017/index-of-selected-words-using-javascript
Tim Down :

You could do this with the new TextRange module of my Rangy library. Rangy's Range object has moveStart() and moveEnd() methods which allow you to expand the range a word at a time in either direction.\n\nHere's a demo: http://jsfiddle.net/timdown/ArMHy/\n\nCode:\n\nvar sel = rangy.getSelection();\nif (sel.rangeCount > 0) {\n var range = sel.getRangeAt(0);\n\n // Expand the range to contain the whole word\n range.expand(\"word\");\n\n // Count all the preceding words in the document\n var precedingWordCount = 0;\n while (range.moveStart(\"word\", -1)) {\n precedingWordCount++;\n }\n\n // Display results\n alert(\"Selection starts in word number \" + (precedingWordCount + 1)); \n}\n",
2012-06-17T23:59:56
yy