Created
December 12, 2023 03:03
-
-
Save apoorvnandan/c31329e31a781c688b96bbed0b09cde1 to your computer and use it in GitHub Desktop.
Basic contenteditable text editor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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