I can easily do execcommand on a contenteditable selection if using a button. However using any other element fails.
http://jsbin.com/atike/edit
Why is this and
You could save the selection by using the mousedown
event on the element being used instead of a button and restore it again after focussing the editable element in the click
event.
I've modified the example code: http://jsbin.com/atike/40/edit. Here's the code:
function saveSelection() {
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
var ranges = [];
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
ranges.push(sel.getRangeAt(i));
}
return ranges;
}
} else if (document.selection && document.selection.createRange) {
return document.selection.createRange();
}
return null;
}
function restoreSelection(savedSel) {
if (savedSel) {
if (window.getSelection) {
sel = window.getSelection();
sel.removeAllRanges();
for (var i = 0, len = savedSel.length; i < len; ++i) {
sel.addRange(savedSel[i]);
}
} else if (document.selection && savedSel.select) {
savedSel.select();
}
}
}
$(function() {
var savedSel;
$('.bold').mousedown(function () {
savedSel = saveSelection();
});
$('.bold').click(function () {
$('#hello').focus();
if (savedSel) {
restoreSelection(savedSel);
}
document.execCommand("bold", false, null);
});
});