JSFiddle - React, Tailwind, and code Playground
HTML
<p>Just click on an icon to add it.</p>
<div class="custom-input">
<div class="selectable-icons">
<span class="label"> Ingredient1 </span>
<span class="label">INGREDIENT 2</span>
<span class="label">INGREDIENT 3</span>
</div>
<div contenteditable="true">
You can type here. <span class="label"> Ingredient1 </span> Add an icon.
</div>
</div><input id="clickMe" type="button" value="clickme" />
CSS
[contenteditable] {
border: 1px solid #000;
margin: 0.4em 0;
line-height: 1.4em;
-webkit-appearance: textfield;
appearance: textfield;
}
img {
vertical-align: top;
max-height: 1.4em;
max-width: 1.4em;
}
.selectable-icons img {
cursor: pointer;
}
span.label.highlight {
background: #E1ECF4;
border: 1px dotted #39739d;
}
span.label {
background: #E1ECF4;
border: 1px dotted #39739d;
}
JavaScript
document.querySelector('.selectable-icons').addEventListener('click', function(e) {
document.querySelector('[contenteditable]').appendChild(e.target.cloneNode(true));
});
document.getElementById("clickMe").onclick = function () { document.getElementsByClassName('label')[0].innerHTML = 'new text';
};
document.querySelector('div').addEventListener('keydown', function(event) {
// Check for a backspace
if (event.which == 8) {
s = window.getSelection();
r = s.getRangeAt(0)
el = r.startContainer.parentElement
// Check if the current element is the .label
if (el.classList.contains('label')) {
// Check if we are exactly at the end of the .label element
if (r.startOffset == r.endOffset && r.endOffset == el.textContent.length) {
// prevent the default delete behavior
event.preventDefault();
if (el.classList.contains('highlight')) {
// remove the element
el.remove();
} else {
el.classList.add('highlight');
}
return;
}
}
}
event.target.querySelectorAll('span.label.highlight').forEach(function(el) { el.classList.remove('highlight');})
});