Search code examples
javascripthtmleventscontenteditablekeydown

Can a user exit a contenteditable with a key?


I currently have a content editable that allows users to change text within a span. I want to make it so that the content editable container closes after the user presses the Enter key.

  container.addEventListener('click', (event) => {
            if (event.target.classList.contains('targetSpan')){
                document.removeEventListener('keydown', keyDownEvents);
                document.addEventListener('keydown', (event) =>{
                    if (event.key === 'Enter'){
                        document.addEventListener("keydown", keyDownEvents);
                       //function to also close contenteditable container
                    }
                });
            }
        });

I currently have an event listener that is removed upon click on the span that has the contenteditable attribute. I want to add back the event listener when the user clicks the enter key. However, I also want the contenteditable container to close


Solution

  • This might work for you.

    var container = document.getElementById("container");
    
    container.addEventListener('click', (event) => {
      if (event.target.classList.contains('targetSpan')){
        container.setAttribute('contenteditable',true);
        container.addEventListener('keydown', checkKey);
      }
    });
    
    container.addEventListener('blur',(event) => {
        container.removeEventListener('keydown',checkKey)
    });
    
    function checkKey(e) {
      if(e.key === 'Enter') {
        container.blur();
      }
    }
    <span class="targetSpan" contenteditable="true" id="container">I'm a dummy text, edit me</span>


    EDIT

    If you don't need the click event, and .targetSpan class checking, you can shorten your code, by doing something like this.

    var container = document.getElementById("container");
    
    container.addEventListener('keydown', checkKey);
    
    function checkKey(e) {
      if(e.key === 'Enter') {
        container.blur();
      }
    }
    

    In this case, there's no need to check for the click event and attach the keydown inside of it. contenteditable=true let's you type inside your element by design. The keydown event listener was left the way it was, in case you need to remove it at some point.