I have a contenteditable div, as shown in HTML below (caret marked by |
).
I would like to remove span.label
when pressing backspace or delete (i.e. the span acts as a single letter, thus to the user it looks as if Name
was deleted in one single keypress)
<div contenteditable="true">
Hallo, <span class="label">Name</span>|,
this is a demonstration of placeholders!
Sincerly, your
<span class="label">Author</span>
</div>
You need to check if the cursor is at the exact position of the end of the span, and if so - remove it:
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');})
});
span.label.highlight {
background: #E1ECF4;
border: 1px dotted #39739d;
}
<div contenteditable="true">
Hallo, <span class="label">Name</span>|,
this is a demonstration of placeholders!
</div>
I didn't implement the
del
key functionality, but the general idea is there and I think you can complete it based on the above example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With