JSFiddle - React, Tailwind, and code Playground

by nrayburn

HTML

<div id="text-div" style="border: red solid 1px; height: 200px;" contenteditable="true">
	<span style="font-size: 12px; font-family=cursive; color: red;">StarterEle</span>
</div>


<select id="font-selector">
	<option>6</option>
	<option>12</option>
	<option>18</option>
</select>
<select id="family-selector">
	<option>sans-serif</option>
	<option>cursive</option>
	<option>system-ui</option>
</select>
<select id="color-selector">
	<option>red</option>
	<option>blue</option>
	<option>black</option>
</select>

JavaScript

const editableDiv = document.getElementById('text-div');
editableDiv.addEventListener('keydown', testFunc);

const sizeSelector = document.getElementById('font-selector');
const familySelector = document.getElementById('family-selector');
const colorSelector = document.getElementById('color-selector');


function testFunc(event){
	event.preventDefault();
	const selection = window.getSelection();
	const parent = selection.anchorNode.parentNode;
	const parentAfter = selection.focusNode.parentNode;
	if (parent !== editableDiv ){
		const sizeValue = sizeSelector.value;
		const familyValue = familySelector.value;
		const colorValue = colorSelector.value;
		if (
			parent.style &&
			parent.style.fontSize === sizeValue + 'px' &&
			parent.style.fontFamily === familyValue &&
			parent.style.color === colorValue
		){
			selection.anchorNode.textContent += event.key;
		} else {
			const newEle = document.createElement('span');
			newEle.textContent = event.key;
			newEle.style.fontSize = sizeValue + 'px';
			newEle.style.fontFamily = familyValue;
			newEle.style.color = colorValue;
			editableDiv.insertBefore(newEle, parentAfter);
		}
	}
}