I am trying to create a contenteditable div where the user can use keyboard shortcuts in order to change the styles. To do this, I am using document.execCommand. Everything works fine, except for when I need to change the fontSize. This is because document.execCommand only does font sizes in ranges of (1-7) and not pixels. To get around this, I retroactively changed all sizes of 7 to be 14.66px (the size I need them to be). However, the fontSize command also creates a font element. The issue is that when the user also uses the highlight command with this element in place, it glitches out the highlight and causes it to be very very short, only extending from the exact top of the text down to the bottom, instead of leaving a couple pixels of padding.
Now, this I could deal with. I'm not that picky. But the issue arises when the user tries to select more text and highlight it. If the text that the user selects INCLUDES text that was apart of the element and was already highlighted, then the previously highlighted text actually gets the padding that I was looking for, but the new text still has the very short highlight.
I'm not quite sure why this occurs and am either looking for an alternate solution that does not require me to make a element or a way to ensure the highlighting is standarized, even when the selections overlap each other.
Here is the code:
window.addEventListener('keydown', function (event) {
if (event.altKey){
if (event.code === 'Digit1') {
//shrink//
document.execCommand('removeFormat', false, false)
changeFont('10px')
}
if (event.code === 'Digit2') {
//remove format//
document.execCommand('removeFormat', false, false)
changeFont('14.66px')
}
if (event.code === 'Digit3'){
//underline//
changeFont('14.66px')
document.execCommand('underline', false, false)
}
if (event.code === 'Digit4'){
//bold//
document.execCommand('bold', false, false)
changeFont('14.66px')
}
if (event.code === 'Digit5'){
//highlight//
document.execCommand('hilitecolor', false, localStorage.getItem("colorSelect"))
changeFont('14.66px')
}
if (event.code === 'Digit6'){
//highlight, bold, and underline//
document.execCommand('removeFormat', false, false)
document.execCommand('hilitecolor', false, localStorage.getItem("colorSelect"))
var fontElements5 = window.getSelection().anchorNode.parentNode
changeFont('14.66px')
fontElements5.style.fontWeight = "bold"
fontElements5.style.textDecoration = "underline";
}
}
});
I've tried to include as much information as possible, but if you are one of the kind people who are willing to help but need more information, please let me know. Any help is appreciated.