LORE Part 2. Check if bold
Lightweight Opensource Richcontent Editor
by Imabot
HTML
<h2>Editor</h2>
<button id="btn-bold"><b>B</b></button>
<div id="editor" contenteditable="true"><p>Select or click on a <b>part of this text</b>.</p><p><br></p><p>The button color should be blue if the text is bold.</p></div>
<h2>HTML output</h2>
<pre id="output"></pre>
<small>More details on <a href="https://lucidar.me/en/rich-content-editor/lightweight-rich-content-editor-part-2-check-if-bold/" target="_blank">my blog</a>.</small>
CSS
#editor {
min-height:30vh;
max-height:80vh;
overflow-y:auto;
white-space: pre-wrap;
background-color: #eaeaff;
}
#editor p {
margin: 0;
}
#output {
background-color: #ffeaea;
}
#btn-bold.active { color:blue; }
JavaScript
let editor = document.getElementById('editor');
let output = document.getElementById('output');
// :::::::::::: BUTTONS ::::::::::::::::::
let btnBold = document.getElementById('btn-bold');
// Set focus to the editor when page is loaded
document.addEventListener("DOMContentLoaded", () => {
editor.focus();
});
// When selection changes
document.onselectionchange = () => {
// Check if the editor is focussed
if (editor === document.activeElement)
{
output.textContent = editor.innerHTML;
if (isSelectionInTag('B')) btnBold.classList.add('active'); else btnBold.classList.remove('active');
}
}
// Check if the current selection
function isSelectionInTag(tag)
{
// Get the current node
let currentNode = window.getSelection().focusNode;
// While the node is not the editor division
while (currentNode.id !== 'editor')
{
// Check if the node is the requested tag
if (currentNode.tagName === tag) return true;
// Move up in the tree
currentNode = currentNode.parentNode;
}
return false;
}