Skip to content

Instantly share code, notes, and snippets.

@apoorvnandan
Created December 12, 2023 03:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apoorvnandan/c31329e31a781c688b96bbed0b09cde1 to your computer and use it in GitHub Desktop.
Save apoorvnandan/c31329e31a781c688b96bbed0b09cde1 to your computer and use it in GitHub Desktop.
Basic contenteditable text editor
document.getElementById("editor").addEventListener("keydown", function (event) {
// Check if Enter is pressed without the Ctrl key
if (event.key === "Enter" && !event.ctrlKey) {
event.preventDefault();
}
// Check if both Ctrl and Enter are pressed
if (event.ctrlKey && event.key === "Enter") {
event.preventDefault();
const selection = window.getSelection();
if (selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
// Insert a line break and a zero-width space to ensure new line
const lineBreak = document.createElement("br");
const zeroWidthSpace = document.createTextNode("\u200B");
range.deleteContents();
range.insertNode(zeroWidthSpace);
range.insertNode(lineBreak);
// Move the cursor after the zero-width space
range.setStartAfter(zeroWidthSpace);
range.setEndAfter(zeroWidthSpace);
selection.removeAllRanges();
selection.addRange(range);
}
}
});
<div id="editor" contenteditable="true" style="border: 1px solid black; min-height: 10px;">
Type your text here...
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment