Categories
JavaScript Answers

How to prevent contenteditable element from adding div on pressing enter with Chrome and JavaScript?

Spread the love

Sometimes, we want to prevent contenteditable element from adding div on pressing enter with Chrome and JavaScript.

In this article, we’ll look at how to prevent contenteditable element from adding div on pressing enter with Chrome and JavaScript.

How to prevent contenteditable element from adding div on pressing enter with Chrome and JavaScript?

To prevent contenteditable element from adding div on pressing enter with Chrome and JavaScript, we can listen for the keydown event on the contenteditable element and prevent the default behavior when Enter is pressed.

For instance, we write

<div class="element" contenteditable="true">
  Sample text
</div>

to add a contenteditable div.

Then we write

document.addEventListener("keydown", (event) => {
  if (event.key === "Enter") {
    document.execCommand("insertLineBreak");
    event.preventDefault();
  }
});

to listen to the document’s keydown event with addEventListener.

In the event listener callback, we check if the key pressed is Enter with

event.key === "Enter"

If it is, we run document.execCommand("insertLineBreak") to insert a line break.

And we call event.preventDefault to prevent the div from being inserted.

Conclusion

To prevent contenteditable element from adding div on pressing enter with Chrome and JavaScript, we can listen for the keydown event on the contenteditable element and prevent the default behavior when Enter is pressed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *