JSFiddle - React, Tailwind, and code Playground

by Tushar Jadhav

HTML

<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);
  });
});