<div id="editor" contenteditable>
Lorem !p$um dolor $!t @met, con$ectetur @d!p!$!c!ng el!t, $ed do e!u$mod tempor !nc!d!dunt ut l@bore et dolore m@gn@ @l!qu@. Ut en!m @d m!n!m ven!@m,
qu!$ no$trud exerc!t@t!on ull@mco l@bor!$ n!$! ut @l!qu!p ex e@ commodo con$equ@t. Du!$ @ute !rure dolor
!n reprehender!t !n volupt@te vel!t e$$e c!llum dolore eu fug!@t null@ p@r!@tur.
</div>
JavaScript
$(function() {
function getCaretPosition(editableDiv) {
var caretPos = 0,
sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
if (range.commonAncestorContainer.parentNode == editableDiv) {
caretPos = range.endOffset;
}
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
if (range.parentElement() == editableDiv) {
var tempEl = document.createElement("span");
editableDiv.insertBefore(tempEl, editableDiv.firstChild);
var tempRange = range.duplicate();
tempRange.moveToElementText(tempEl);
tempRange.setEndPoint("EndToEnd", range);
caretPos = tempRange.text.length;
}
}
return caretPos;
}
function getCurrentWord(el, position) {
var word = '';
// Get content of div
var content = el.textContent;
// Check if clicked at the end of word
position = content[position] === ' ' ? position - 1 : position;
// Get the start and end index
var startPosition = content.lastIndexOf(' ', position);
startPosition = startPosition === content.length ? 0 : startPosition;
var endPosition = content.indexOf(' ', position);
endPosition = endPosition === -1 ? content.length : endPosition;
return content.substring(startPosition + 1, endPosition);
}
$('#editor').on('keyup keydown paste cut mouseup', function() {
var caretPosition = getCaretPosition(this);
var word = getCurrentWord(this, caretPosition);
console.log(word);
});
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.