Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading