Reputation: 11480
const elementEditing = document.getElementById('example');
elementEditing.addEventListener("keydown", onkeydownInEditable);
function onkeydownInEditable(e, KeyboardEvent) {
if (e.key === "Enter") {
e.preventDefault();
}
if (e.key === "Backspace") {
console.log('is el[notContentDeletable] just in front cursor and will be deleted ?')
} else if ( e.key === "Delete") {
console.log('is el[notContentDeletable] just behind cursor and will be deleted ?')
}
}
<div id="example" contentEditable="true">
aaaaa 1<input notContentDeletable>2 bbbbb
</div>
I want to prevent that an element with [notContentDeletable] attribute gets deleted by "del" or "backspace".
(in jsfiddle)
if im between 1
and input
and press del
the input will be deleted. I want to prevent this.
if im between input
and 2
and press backspace
the input will be deleted. I want to prevent this.
So how can I get the element next to or after the cursor? Is that possible?
Upvotes: 0
Views: 657
Reputation: 4883
You can use window.getSelection()
to get information about the current cursor position in the currently focused element.
Then based on that, you could implement your desired behaviour.
Note: because getSelection doesn't work well inside of input
and textarea
tags, but already works correctly with delete and backspace, you could just return if the event target is either of them.
import "./styles.css";
const elementEditing = document.getElementById("example");
elementEditing.addEventListener("keydown", onkeydownInEditable);
function onkeydownInEditable(e, KeyboardEvent) {
if (e.key === "Enter") {
e.preventDefault();
}
if (e.key === "Backspace") {
if (
e.target instanceof HTMLInputElement ||
e.target instanceof HTMLTextAreaElement
) {
return;
}
const selection = getSelection();
const currentNode = selection.focusNode;
if (!(currentNode instanceof Text)) {
e.preventDefault();
}
} else if (e.key === "Delete") {
if (
e.target instanceof HTMLInputElement ||
e.target instanceof HTMLTextAreaElement
) {
return;
}
const selection = getSelection();
const offset = selection.focusOffset;
const currentNode = selection.focusNode;
if (currentNode.length === offset) {
e.preventDefault();
}
}
}
<div id="example" contentEditable="true">
aaaaa 1<input notContentDeletable>2 bbbbb
</div>
Working CodeSandbox link: https://codesandbox.io/s/cranky-architecture-946p5?file=/src/index.js
Upvotes: 1
Reputation: 31
It creates a range that starts at the start of the editable element and ends immediately before the caret, gets the range's text and returns the last character of that range.
Upvotes: 2