Andre Elrico
Andre Elrico

Reputation: 11480

get element just in front or after the cursor

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)

So how can I get the element next to or after the cursor? Is that possible?

Upvotes: 0

Views: 657

Answers (2)

deckele
deckele

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

Saifee
Saifee

Reputation: 31

Check this question.

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

Related Questions