We have an editable div and we want to change the style of the text, selected by the user, on clicking our button; just same as this editor's bold or italic button.
But when we click on the button our selected text get deselected.
So how to keep our selected text highlighted even if the focus from the editable is 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);
}