Search code examples
javascriptdom-eventscontenteditableexeccommand

codeBlock wrapped in <pre> inside contenteditable breaks on pressing Enter


In my custom-editor wrapping up the code in <pre> tags works fine. I would like to visually organize the pasted code for better readability. For that I need blank lines in between chunks of code. But instead of a empty line, when I press Enter, the whole code block breaks into two, with new one wrapped in its own pre-tag. The code below is supposed to be in a single-block with an empty line between example_function and another_example_function()

precode issue

FYI, the contenteditable class is set to have style="display:inline-block" to prevent div.wrapper on every line. Possibly relevant CSS info - pre { white-space: pre-wrap;}. I am on chrome 83.xx. Let me know if you need any more info. Below is what I tried and failed:

//there could be several code-blocks so running a loop to get all
let preTags = document.querySelector('.custom_editor').querySelectorAll('pre')
if (preTags) {
  preTags.forEach(function(item) { // attaching an event-listener to each code block
    item.addEventListener('click', function(e) {
      if (e.keyCode === 13) { //on enter just need a empty new line
        document.execCommand('insertHTML', false, '<br>');
        return false;
      }
    })
  }
}

HTML

<div class="content" style="display:inline-block;" contenteditable="true"></div>

Solution

  • The nested pretags eg. contenteditable>pre do not seem like an ideal setup for events like 'keypress', 'keydown' and 'keyup' as they did respond to these events in my case. The 'click' event within pretags worked but did not process the if (e.key === 'Enter') check, so I did not follow that route.

    Instead of listening to events for each pretag, I attached a listener to the container only and all of sudden my custom setting for enter-event was working inside and outside all pretags within container. Eventually I can get the empty lines within my pretags on pressing the Enter key.

    document.querySelector('.custom_editor').addEventListener('keypress', someFunc)
    function someFunc(e){
        if (e.key === 'Enter') { 
            document.execCommand('insertHTML', false, "<br>");
            e.preventDefault()
        } 
    }