I am faced with following issue:
When I put cursor to some position and then apply execCommand('bold') in all browsers except IE next typed text will be bold, but in IE it makes all word bold.
Here is images to make it more clearly.
Normal/expectable behavior (Crhome, Firefox etc.):
Behavior in IE:
Below is codesnippet and it also could be found on jsfiddle.
var lastCaretIndex = null;
document.addEventListener('selectionchange', function(event) {
var taget = event.target;
if (taget.activeElement.id == 'main-input') {
lastCaretIndex = getSelectionRange();
console.log(typeof lastCaretIndex);
console.log(lastCaretIndex);
}
});
function afterFocus() {
var s = null;
if (window.getSelection) {
s = window.getSelection();
} else {
s = document.getSelection();
}
if (lastCaretIndex == null) {
lastCaretIndex = document.createRange();
} else if (s.rangeCount > 0) {
s.removeAllRanges();
s.addRange(lastCaretIndex);
}
}
function getSelectionRange() {
var sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
return sel.getRangeAt(0);
}
} else if (document.selection) {
return document.createRange();
}
return null;
}
$(document).on('click', '.icon-bold', function () {
document.getElementById('main-input').focus();
afterFocus();
document.execCommand('bold');
handleButtonActiveState($(this));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="main-input" contenteditable="true">Hello world!</div>
<button type="button" class="icon-bold">Bold</button>
Can somebody please help me. I tried to find solution in Internet but didn't get any results. It seems like it doesn't related with TextRange.
P.S. please let me know if something else is needed.