I'm sure there is a better way to solve this, so I hope someone else will also shed some light on this issue. This solution uses some trial and error for moving the range about - if things so wrong, it is reverted to the original state.
I hope this helps!
Here is the code:
<html>
<body>
<script>
window.setInterval(
function () {
var selection = document.selection;
var range = document.selection.createRange();
var parentEl = range.parentElement();
// Make a duplicate range to revert to if things go wrong.
range2 = range.duplicate();
range.moveStart('character', 1);
if (range.parentElement() != parentEl) {
// We've left the original parent (which is bad), so revert to the original range. We're probably at the end of the textarea.
range = range2.duplicate();
}
range.moveStart('word', -1);
// Make a new duplicate range to revert to.
range2 = range.duplicate();
// Move the end of the range one backwards, then forward to the end of the word.
range.moveEnd('character', -1);
range.moveEnd('word', 1);
if (range.parentElement() != parentEl) {
range = range2.duplicate();
while (range2.parentElement() == parentEl) {
range.moveEnd('character', 1);
range2 = range.duplicate();
}
}
var wort = range.text.replace(/^\s\s*$/, '').replace(/\s\s*$/, '');
document.getElementById("ausgabe").innerHTML = wort;
}, 100
)
</script>
<textarea id="ta" rows="10" cols="40">At vero eos et accu-samus et iusto? Odio, dignissimos. ducimus qui bländitiis praeséntium voluptatèm deleniti atque corrupti quos</textarea>
<p>[<span id="ausgabe"></span>]</p>
</body>
</html>