Reputation: 1536
I'm trying to create a very simple text editor using jquery.
I can get the selected/highlightet texts. and I can also wrap it in <strong>text text</strong>
as well.
However, when i append it into the div again, it doesn't replace the highlighted text. it just appends it to the current texts.
To explain this better, i've created this fiddle:
https://jsfiddle.net/o2gxgz9r/5502/
and this is my jquery code:
$('#showBold').on('click', function(e){
e.preventDefault();
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
var header = getSelectionText();
var boldHeader = header.replace(header, '<strong>'+header+'</strong>');
$('#details00').append(boldHeader);
});
Select the texts in the Div and click on the button to see the issue.
Could someone please advise on this issue?
Upvotes: 0
Views: 744
Reputation: 298136
You won't be able to do this with just text replacement. The selection API lets you modify the contents of the selection, so making the selected text bold is not that hard:
var $textarea = $('#textarea');
$('#bold').on('click', function(e){
var selection = window.getSelection();
// Make sure something was selected
if (!selection.rangeCount) {
return;
}
var range = selection.getRangeAt(0);
var $container = document.createElement('b');
// Move the contents of the selection into the container
$container.appendChild(range.extractContents());
// Move the container into the now empty range
range.insertNode($container);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="bold">Make Bold</button>
<div id="textarea" contenteditable>Content Here....</div>
There are a bunch of corner cases and bugs that you have to account for, however, so you may want to just use some pre-built rich text editor.
Upvotes: 2