My objective is to create a custom text editor with basic functionalities such as bold, italic, underline, and paragraph styling only. The purpose of this project is for studying purposes.
The main challenge I am facing is avoiding color-based interactions through JavaScript and utilizing color interaction via CSS only. Hence, I am aiming to achieve this using pure JS & CSS without any external library.
To implement this, I have utilized a checkbox element to toggle bold font within a contenteditable div. However, the issue arises when the checkbox clears the selection in HTML before obtaining the range of the selected text from div.innerHTML. How can I resolve this dilemma?
function actionBold122(e){
let editor = document.getElementById('editor')
let input = e.getElementsByTagName('input')[0]
if(input != null){
input.checked = !input.checked
}
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var arr = []
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
arr.push(sel.getRangeAt(i).cloneContents().textContent);
}
html = arr.join();
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
alert(html)
}
input{
display: none;
}
input:checked+svg{
background-color: rgb(194, 10, 10);
fill: #fff;
}
label{
cursor: pointer;
}
#editor{
width: 50%;
min-height: 40px;
background-color: antiquewhite;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body>
<label onclick="actionBold122(this); return false">
<input class="none" type="checkbox" name="0" checked>
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M15.6 10.79c.97-.67 1.65-1.77 1.65-2.79 0-2.26-1.75-4-4-4H7v14h7.04c2.09 0 3.71-1.7 3.71-3.79 0-1.52-.86-2.82-2.15-3.42zM10 6.5h3c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5h-3v-3zm3.5 9H10v-3h3.5c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5z"/><path d="M0 0h24v24H0z" fill="nonext/html"></svg>
</label>
<div id="editor" contenteditable>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim omnis ea, voluptas maxime perspiciatis praesentium magni repellendus earum suscipit sint. Veritatis fuga adipisci accusantium similique distinctio vero tenetur ipsam fugiat.</p>
</div>
<button onclick="actionBold122(this)">Get Text</button>
</body>
</html>
Current code:
https://i.sstatic.net/6l39l.gif
I aim to achieve similar functionality to the "Get Text" button with the checkbox input. If you have any ideas on how to address this issue, please feel free to suggest. Thank you in advance!