Home > Enterprise >  Can a user exit a contenteditable with a key?
Can a user exit a contenteditable with a key?

Time:01-07

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

CodePudding user response:

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  contenteditable="true" id="container">I'm a dummy text, edit me</span>

  • Related