JSFiddle - React, Tailwind, and code Playground

by giovanni gokhan morkoc

HTML

<div class="colorpicker"></div>
<div contenteditable="true">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>

CSS

.colorpicker {
    border: solid thin black;
    width: 20px;
    height: 20px;
}

JavaScript

var colorpickerOptions = {
    select: function (event, color) {
        var color_in_hex_format = color.formatted;
        var html = $('[contenteditable]').html();
        console.log(html);
        $('[contenteditable]').html(html.replace(selection,'<span style="color:#'+color_in_hex_format+'">'+selection+'</span>'));
        $('.colorpicker').css('background-color', '#' + color_in_hex_format);
    } ,
    inline: false
};
var selection = "";
$('[contenteditable]').on('mouseup',function(){
selection = getSelectionHtml();
    
});
$('.colorpicker').colorpicker(colorpickerOptions);
function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}