In this article, we will be looking at how to build a simple editor such as the WordPress Gutenberg editor. Here is the code for the code snippet.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Modern HTML Editor</title>
<style>
#editor {
width: 100%;
height: 300px;
border: 1px solid #ccc;
padding: 5px;
font-family: Arial, sans-serif;
}
button {
margin: 5px;
}
</style>
</head>
<body>
<div>
<button onclick="formatText('bold')">Bold</button>
<button onclick="formatText('italic')">Italic</button>
<button onclick="formatText('underline')">Underline</button>
<button onclick="insertLink()">Insert Link</button>
</div>
<div id="editor" contenteditable="true"></div>
<script>
function formatText(command) {
document.execCommand("styleWithCSS", null, true);
document.execCommand(command, false, null);
}
function insertLink() {
var url = prompt("Enter the URL:");
if (url) {
document.execCommand("createLink", false, url);
}
}
</script>
</body>
</html>
Here is the output.
Try it yourself.