0

I have a div that has contenteditable set to true and then two more div's inside being added dynamically. For example

<div contenteditable='true'>
    <div id='1'>
        <span>Something Editable</span>
        <span contenteditable='false'>Something NOT Editable</span>
    </div>
    <div id='2'>
        <span>Second Something Editable</span>
        <span contenteditable='false'>Something NOT Editable</span>
    </div>
</div>

If I have my cursor in the span that says Second Something Editable, and I press backspace, it moves the text in this span to the first div, like the code below, which I do not want.

<div contenteditable='true'>
        <div id='1'>
            <span>Something Editable</span>
            <span contenteditable='false'>Something NOT Editable</span>
            Second Something Editable.
        </div>
        <div id='2'>
            <span contenteditable='false'>Something NOT Editable</span>
        </div>
    </div>

And again, if I press enter in the First div (div id=1) on the line that says Second Something Editable, it would create a new div with id=1 and put the content there. Can anyone tell me how to fix this. Thanks

bna-it
  • 71
  • 1
  • 8

1 Answers1

1

To get around your first problem I'd simply add the contenteditable flag directly to the <span> which should be editable and not it's parent container.

The second problem is a bit more tricky. You can avoid the creation of a new <div> by adding a keydown listener, intercepting the return key press and call event.preventDefault() to stop the browser from doing it's default action.

Update:

If you do not want to set the parent <div> to be editable you can use the same trickery as for the return press. This time we just need to intercept the backspace keypress (keycode 8) and check if the cursor is currently at the beginning of the line - so the user is still able to delete text.

Here's an example:

document.addEventListener("keydown", function(e) {
  if (e.keyCode == 13) {
    e.preventDefault();
  }
    if (e.keyCode == 8 && document.getSelection().anchorOffset == 0) {
    e.preventDefault();
  }
});
<div contenteditable='true'>
  <div id='1'>
    <span >Something Editable</span>
    <span contenteditable='false'>Something NOT Editable</span>
  </div>
  <div id='2'>
    <span contenteditable='true'>Second Something Editable</span>
    <span contenteditable='false'>Something NOT Editable</span>
  </div>
</div>
obscure
  • 11,916
  • 2
  • 17
  • 36
  • The preventDefault() works perfectly, but I do not want to just add contenteditable to the span, because I want the user to be able to edit content in the parent div, if the span is not there as they are being added dynamically. Actually I have a list of countries and if the user selects one it creates a new div-> puts the country name in the first span and some details in the second and appends it to the main div. – bna-it Aug 07 '20 at 00:42