End editing in contenteditable on return key

Viewed 727

I created a html table and set the td elements to contenteditable = true. If I click somewhere else on the page I "end" the editing of the content which means the cell isn't highlighted anymore and typing characters doesn't add them to the cell.

I want to achieve this on pressing the return key. I already have a key listener to prevent the user from inserting line breaks when pressing the return key:

document.addEventListener('keydown', function (event) {
    if (event.key === 'Enter') {
        event.preventDefault();
        var value = event.target.innerHTML;
        // do something with the value
    }
});

How do I "end" editing (something like jump out of the cell) on pressing the return key?

The td elements all look like this:

<td class="memory-cell" id="memory-cell-45" data-cell-number="45" width="100" contenteditable="true">0</td>

UPDATE: I ended up on setting contenteditable = true on click and removing the contenteditable attribute on return key press.

1 Answers

Bind the onkeydown to document or preferably the editable element, and then remove the contenteditable property on keydown, if it's the Enter key that is pressed.

You can also bind to document.querySelector(".memory-cell").onkeydown if youwant to disable it outside div.

document.onkeydown = function(event) {
  if (event.key === 'Enter') {
    event.preventDefault();
    document.querySelector(".memory-cell").removeAttribute('contenteditable');
  }
}

function enableEditing(element){
  //Adds the content editable property to passed element
  element.setAttribute('contenteditable', true)
  //Focuses the element
  element.focus()
}
<table border="1">
  <tr>
    <td class="memory-cell" onclick="enableEditing(this)" id="memory-cell-45" data-cell-number="45" width="100" contenteditable>0</td>
  </tr>
</table>

PS: The additional table element in below snippet was added for reference only

Related