I'm trying to make a basic text editor in HTML. I've got an editable div tag so far, and by using keyboard shortcuts, you can format it. However, I want it so that there are a couple of buttons which can bold, italicize, underline and change the color of the text. I'm using basic jQuery and JS for this.
Here's (roughly) my code so far:
$('.text-editor').each(function(){
this.contentEditable = true;
});
div.text-editor {
width: 200px;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>
CodePudding user response:
This is a simple text editor with some simple buttons and keyboard shortcuts . Hope it can help you
<html>
<head>
<title>Make simple text editor</title>
<meta charset="UTF-8" />
</head>
<body>
<div>
<button type="button" onclick="onItalic()">italic</button>
<button type="button" onclick="onBold()">bold</button>
<button type="button" onclick="onUnderline()">underline</button>
</div>
<textarea name="example" id="example_id" cols="30" rows="10"></textarea>
<script>
const textarea = document.getElementById("example_id");
function onItalic() {
textarea.style.fontStyle = "italic";
}
function onBold() {
textarea.style.fontWeight = "bold";
}
function onUnderline() {
textarea.style.textDecoration = "underline";
}
function onKeyboardShotcut(e) {
if (e.ctrlKey && e.key === "i") {
onItalic();
} else if (e.ctrlKey && e.key === "b") {
onBold();
} else if (e.ctrlKey && e.key === "u") {
onUnderline();
}
}
document.addEventListener("keyup", onKeyboardShotcut, false);
</script>
</body>
</html>
CodePudding user response:
You can try this approach on jquery.
$('.text-editor').each(function(){
this.contentEditable = true;
});
$('.italic').click(function(){
$('.text-editor').css("font-style", "italic");
$('.text-editor').css("font-weight", "initial");
});
$('.bold').click(function(){
$('.text-editor').css("font-style", "initial");
$('.text-editor').css("font-weight", "bold");
});
div.text-editor {
width: 50px;
height: 50px;
}
.text-editor:focus-within {
font-style: initial;
font-weight: initial;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div >Hello</div>
<button >Italic</button>
<button >Bold</button>
</body>