skip to Main Content

All I need is to replace <div><br></div> or <br> with just a new line n when a user pressing the "Enter" key.

I’ve got a code:

divEl.addEventListener("keydown", e => {
    if (e.key === "Enter") {
        e.preventDefault();

        const selection = document.getSelection();
        const range = selection.getRangeAt(0);
        range.deleteContents();

        const newLineNode = document.createTextNode("n");

        range.insertNode(newLineNode);
        range.collapse();
    }
});

The above code works, but with some glitches. In chrome, I need to press Enter twice to go to a new line, in FireFox, it’s enough to press one time.
I’ve got no idea what could be wrong. Is there a way to make this work in the right way in all modern browsers?

P.S. Don’t even try to google it or search here. I’ve tried it many times. Nothing is working…

2

Answers


  1. Chosen as BEST ANSWER

    I found the problem. In fact, I made an omission in describing my problem. And this problem is present in all browsers...

    Double-pressing is required when the cursor is placed at the end of the contentEditable div. A double n must be added to solve this problem.


  2. A simple solution could be to not prevent adding the <br> but to simply replace it.

    const div = document.querySelector("#container");
    div.addEventListener("keydown", replaceLineBreak);
    div.addEventListener("keyup", replaceLineBreak);
    
    function replaceLineBreak(e) {
      div.querySelector("br")?.replaceWith("n");
    }
    #container {
      white-space: pre;
      padding: 1rem;
      background: #FFB;
    }
    <div id="container" contenteditable="true"></div>

    maybe you run this code only when Enter is pressed

    if (e.key === "Enter") div.querySelector("br")?.replaceWith("n");
    

    I don’t know your exact use case and how this may interfere with copy-paste, drag’n’drop, or holding a key pressed.

    Or you could do a debounced

    for (const br of div.querySelectorAll("br")) {
      br.replaceWith("n");
    }
    

    If you can live with the <br>s being in your markup for a second or two.

    Depends all on your exact use case.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search