Bold highlighted text in a contentEditable div using pure JavaScript without libraries like jQuery
We have an editable div and we want to change the style of the text selected by the user when our button is clicked; just like this editor in bold or italic.
But when we click on the button, our selected text is not selected.
So, how to keep the selected text, even if the focus from the editable is turned off and change the style.
My code:
Editable Div:
var textbox= document.createElement("div");
textbox.setAttribute("contenteditable", "true");
Button:
var bold = document.createElement("div");
bold.innerHTML = "B";
Button Click:
bold.addEventListener("click", function(){
getSelectedText();
},false);
function getSelectedText()
{
var html = "";
if (window.getSelection) {
html = window.getSelection().toString();
}
else if (document.selection && document.selection.type != "Control") {
html = document.selection.createRange().text;
}
alert(html);
}
source to share
You can get the selection by listening contentEditable
onmouseup
and store it in a variable. After you hit the div, you will revert the selection to return what it was:
Javascript:
var range = "";
function getSelected() {
var selection = window.getSelection()
range = selection.getRangeAt(0);
}
function reselect() {
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
jsfiddle DEMO
used button and div for buttons so you can see the difference.
source to share
Either use an event mousedown
instead of an event click
, or set a button <div>
to resist selection.
See this answer for details .
source to share