Search code examples
javascriptcsshtmlmarkup

HTML Contenteditable only on one line


I have an app that has different lists a user can make, and the user can edit the name, but if he types a new name, he should be able to type enter and go many lines down.

I want to make the editable area only one line. I added a max height and overflow hidden, but that literally only hides what the other things you type, and I want only one line to stay.

code:

h3 {
  height: 25px;
  max-height: 25px;
  overflow: hidden;
}
<h3 contenteditable="true">To Do List</h3>
<section id="pageOne" contenteditable="true">
    <li style="color: #393939;"></li>
</section>

pictures:

enter image description here enter image description here


Solution

  • As @TarasDanylyuk said, you can use keydown combined with preventDefault() to accomplish that.

    Here's a working example:

    document.getElementById('pageOne').addEventListener('keydown', function(e) {
      if (e.keyCode == 13) {    // if Enter has been pressed
        e.preventDefault();
      }
    });
    h3 {
      height: 25px;
      max-height: 25px;
      overflow: hidden;
    }
    <h3 contenteditable="true">To Do List</h3>
    <section id="pageOne" contenteditable="true">
      <li style="color: #393939;"></li>
    </section>

    If you want to remove focus when Enter is pressed, you can do so by adding this line after the preventDefault() call:

    e.target.blur();