<html>
<body>
<div id="textareaId" contenteditable="true">
Hello there
</div>
<button onclick=selectText(0,4)>Click to select</button>
<button onclick=deleteSelectedText()>Click to delete <button>
<script>
// Assuming 'textareaId' is the ID of your contenteditable div
const contenteditableDiv = document.getElementById('textareaId');
// Function to select a range of text within a contenteditable div
function selectText(start, end) {
const range = document.createRange();
range.setStart(contenteditableDiv.firstChild, start);
range.setEnd(contenteditableDiv.firstChild, end);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
// Function to delete the currently selected text
function deleteSelectedText() {
const selection = window.getSelection();
if (!selection.isCollapsed) {
selection.deleteFromDocument();
}
}
contenteditableDiv.addEventListener('keydown', (event) => {
if (event.key === '<' || event.key === 'Delete') {
selectText(0, 5);
}
if (event.key === 'Backspace' && !window.getSelection().isCollapsed()) {
event.preventDefault(); // Prevent default backspace behavior
selectText(window.getSelection().anchorOffset, window.getSelection().focusOffset);
} else if (event.key === 'Backspace' && window.getSelection().isCollapsed()) {
deleteSelectedText(); // Delete highlighted text on second backspace
}
});
// Example usage: select and delete text from 10th to 20th character`your text`
</script>
</body>
</html>
The selected word seems to be getting deleted on the first backspace. how do I change the function to highlight it first on backspace and then on second, delete it fully. I figured the highlighted area is just replace immediately on keydown so needs a different logic.