JSFiddle - React, Tailwind, and code Playground

by Vedant_Terkar

HTML

<div contenteditable="true" id="editable"></div>

CSS

#editable {
    border: 1px solid lightgreen;
    outline:none;
    height:500px;
    transition:all ease 1.0s;
    padding:5px;
}
#editable:focus{
    background:#eee;
}

JavaScript

var selection, range;
var editable=$("#editable").get(0);

// Populates selection and range variables
function captureSelection(e) {
    // Don't capture selection outside editable region
    var isOrContainsAnchor = false,
        isOrContainsFocus = false,
        sel = window.getSelection(),
        parentAnchor = sel.anchorNode,
        parentFocus = sel.focusNode;

    while(parentAnchor && parentAnchor != document.documentElement) {
        if(parentAnchor == $("#editable").get(0)) {
            isOrContainsAnchor = true;
        }
        parentAnchor = parentAnchor.parentNode;
    }

    while(parentFocus && parentFocus != document.documentElement) {
        if(parentFocus == editable) {
            isOrContainsFocus = true;
        }
        parentFocus = parentFocus.parentNode;
    }

    if(!isOrContainsAnchor || !isOrContainsFocus) {
        return;
    }

    selection = window.getSelection();

    // Get range (standards)
    if(selection.getRangeAt !== undefined) {
        range = selection.getRangeAt(0);

    // Get range (Safari 2)
    } else if(
        document.createRange &&
        selection.anchorNode &&
        selection.anchorOffset &&
        selection.focusNode &&
        selection.focusOffset
    ) {
        range = document.createRange();
        range.setStart(selection.anchorNode, selection.anchorOffset);
        range.setEnd(selection.focusNode, selection.focusOffset);
    } else {
        // Failure here, not handled by the rest of the script.
        // Probably IE or some older browser
    }
}

// Recalculate selection while typing
$(document).ready(function(){
$("#editable").keyup(function(e){
captureSelection(e);
}).mousedown(function(e) {
    $(this).addClass('selecting');
}).blur(function(e) {
    var cursorStart = document.createElement('span'),
        collapsed = range?!!range.collapsed:null;

    cursorStart.id = 'cursorStart';
    cursorStart.appendChild(document.createTextNode('—'));

    // Insert beginning cursor...