Megaredačák - tes custom znaky na pr.tlačitku
by Petr Haluza
HTML
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="editable" contenteditable="true">Klikni pravým tl </div>
<div id="contextMenu">
<a href="#" class="char-insert">±</a>
<a href="#" class="char-insert">≥</a>
<a href="#" class="char-insert">µ</a>
<a href="#" class="char-insert">©</a>
<a href="#" class="char-insert">®</a>
<a href="#" class="char-insert"> <sub>ss</sub> </a>
<a href="#" class="char-insert"> <span class="red">red</span> </a>
<a href="#" class="char-insert">→</a>
<a href="#" class="char-insert">→</a>
<a href="#" class="char-insert">©</a>
<a href="#" class="char-insert">®</a>
<a href="#" class="char-insert">π</a>
<a href="#" class="char-insert">→</a>
<a href="#" class="char-insert">©</a>
<a href="#" class="char-insert">®</a>
<a href="#" class="char-insert">π</a>
</div>
CSS
#contextMenu { position: absolute; display: none; background: #fff; border: 1px solid #777; box-shadow: 0 2px 5px rgba(0,0,0,0.2); padding: 5px; z-index: 9999; }
#contextMenu a { display: block; padding: 4px 6px; text-decoration: none; color: #333; cursor: pointer; }
#contextMenu a:hover { background-color: #eee; }
#editable {
width: 400px;
height: 120px;
border: 1px solid #ccc;
padding: 6px;
margin-top: 50px;
}
.red {color:red}
JavaScript
$(document).ready(function() {
let savedRange = null; // Save selection whenever the user changes it inside the editable // Save selection on various events inside the editable element
$('#editable').on('mouseup keyup mouseup', function() {
savedRange = saveSelection();
}); // Show custom menu on right-click inside the editable area
$('#editable').on('contextmenu', function(e) {
e.preventDefault(); // Save the latest selection just in case
savedRange = saveSelection(); $('#contextMenu') .css({ top: e.pageY + 'px', left: e.pageX + 'px', 'font-size': '18px', 'column-count': '2' }) .show(); }); // Hide menu when clicking outside the context menu or the editable region
$(document).on('click', function(e) {
if (!$(e.target).closest('#contextMenu, #editable').length) {
$('#contextMenu').hide();
}
}); // Inserting the clicked character or HTML element at the current cursor position
$('.char-insert').on('click', function(e) { e.preventDefault(); restoreSelection(savedRange); // Get the inner HTML so that tags (like <sub>) are preserved const
contentToInsert = $(this).html(); // Use execCommand with 'insertHTML' to insert HTML content at the caret
document.execCommand('insertHTML', false, contentToInsert); $('#contextMenu').hide(); }); // Helper function to save the current selection
function saveSelection() {
const sel = window.getSelection();
if (sel.rangeCount > 0) { return sel.getRangeAt(0);
} return null;
} // Helper function to restore a saved selection
function restoreSelection(range) { if (range) {
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
});