4

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);
    }
David Thomas
  • 249,100
  • 51
  • 377
  • 410
Piyush Srivastava
  • 357
  • 1
  • 4
  • 21

2 Answers2

2

You can get the selection by listening to your contentEditable's onmouseup and store it in a variable. After you clicked a div, you restore the selection to back 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 a button and a div for buttons so you can see the difference.

Samurai
  • 3,724
  • 5
  • 27
  • 39
1

Either use the mousedown event instead of the click event or set the <div> button to be unselectable.

See this answer for details.

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536