0

I'm trying to copy the innerHTML of a contenteditable div to a javascript variable. When I press enter inside of a contenteditable div, and then copy the innerHTML to a variable I want the text to look like this:

this
is
some
text

Notice the line breaks.

But by default, when you press enter in a contenteditable div this happens to the html.

this <div>is</div> <div>some</div> <div>text</div>

I can acheive the desired behavior by holding shift and pressing enter, but is there a way to set this up so I don't have to hold shift?

Just for reference, I don't want something like this:

this

is

some

text
briann
  • 143
  • 7
  • I would make sure that you are able to post [mcve] – imvain2 Aug 31 '22 at 22:12
  • There is no minimal reproducible example because I don't have any code. That's why I'm asking here. Even a point in the right direction would be fine. – briann Aug 31 '22 at 22:25
  • Is this what you are looking for? https://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome – science fun Aug 31 '22 at 22:46
  • thanks 'science fun'! I wasn't able to find that thread while Googling. Excellent point in the right direction. I added my working solution as an answer. Thank you!! – briann Aug 31 '22 at 22:48

1 Answers1

0

Ok, I found a solution

var contentArea = document.querySelector('.content-area');

contentArea.addEventListener('keypress', function(event) {
    // enter keycode is 13
    if (event.keyCode == 13 && event.shiftKey == false) {
      event.preventDefault(); 
      document.execCommand("insertLineBreak");    
    } 
});

contentArea would obviously depend on what element you want to add the eventListener to.

briann
  • 143
  • 7