I have a to do app and I was requested to add more functionality, such as: add some buttons for Bold and Italic text. In a input, after I press the Bold button, the text that is going to be typed to be bolded, leaving the previous text (the one before I pressed the Bold button) the way it was, regular. I understood that there's no way to bold a section of text in a input, so I simulated a input with a div :
const div = document.querySelector('div');
div.innerHTML = '';
const bold = document.getElementById('boldBtn');
const italic = document.getElementById('italicBtn')
bold.style.backgroundColor = 'white';
let previousText = '';
let boldString = '';
boldBtn.addEventListener('click', () => {
boldBtn.classList.toggle('bold-selected');
if (boldBtn.classList.contains('bold-selected')) {
boldBtn.style.backgroundColor = "gray";
previousText = div.innerHTML;
console.log(previousText)
div.addEventListener('keydown', boldText)
}
else {
bold.style.backgroundColor = "white";
div.removeEventListener('keydown', boldText);
}
})
function boldText(e) {
div.innerHTML = div.innerHTML.substr(1)
console.log("Previous text: " + previousText);
const NOT_ALLOWED = ['Backspace', 'Shift', 'Control', 'Alt'];
if (!NOT_ALLOWED.includes(e.key)) {
boldString += e.key;
console.log("Bold text: " + boldString)
console.log(previousText + boldString)
div.innerHTML = previousText + "<strong>" + boldString + "</strong>"
}
}
div {
border: 1px solid black;
width: 200px;
height: 20px;
}
.font-style {
border: 1px solid blue
}
<div contenteditable="true"></div>
<button id="boldBtn" class="font-style">Bold</button>
<button id="italicBtn" class="font-style">Italic</button>
Try to write something like "cool" in the div then press the Bold button, then type a letter. You'll see that the div gets this innerHTML: letter+cool+boldletter. And the cursor is set at the beginning of the div content. Please help me or at least give a hint to accomplish the wanted behavior! I spent 3-4 hours already and I am ready to give up...
EDIT: I think I didn't make it clear: I don't want to make the entire content of the div be bold, but just a portion/section/part of it. If no button is pressed, the text that is gonna be written should be regular, if the Bold button is pressed, the text that is gonna be written should be Bold, the same with the Italic button. Maybe if the Bold and Italic are selected at the same time, the future text should be bold and italic. But that's another question... An example of what I want is https://html-online.com/editor/ . Remove the default text and just write words on the left panel, and try to use the bold, italic buttons above. In the left panel there will be the HTML generated code. I need the same functionality...