It is nontrivial, mainly because of the hierarchical nature of the document.
A restricted functionality which will get you the previous word as long as it is in the same element, in non-IE browsers:
// get the selection
var sel = window.getSelection();
// get the element in which the selection is made, and the start and end position
var node = sel.anchorNode;
var from = sel.anchorOffset;
// let's see what's before the selection
var textBeforeWord = node.textContent.substring(0, from);
var match = textBeforeWord.match(/(\w+)\s+/);
var previousWord = match[1];
This gets much more complicated when you consider the possibility that a word could be the first thing in its element, or that a selection might be across elements, when you would need to navigate the DOM hierarchy to hunt the previous element. It is also complicated by the fact that you would need to do it twice, completely differently (since IE's API is totally different).
EDIT In case of a <textarea>
element, it gets much simpler, as you don't need to worry about the selection spilling over the element. For IE you will have to do some gymnastics, since it does not support selectionStart
, as described here.
var node = document.getElementById('mytextarea');
var from = node.selectionStart;
var textBeforeWord = node.textContent.substring(0, from);
// the rest is the same as above
Name : Abdul Naeem
. Onclick will be fired on completenot on portion of p. However whatever you want can be achieved if they are in seperate element like--
Name
:Abdul
Naeem
– RahulB Nov 11 '14 at 07:16