Balázs Varga
Balázs Varga

Reputation: 1856

How can I prevent removing the selection from text after a click?

I'm working on an admin-panel where the inputs are contenteditable divs. I also have a toolbar (containing some formatting buttons), that shows up if you have any selected text inside the div, and will be removed if not.

The problem is, that when I click to any button in the toolbar, the selection from the document will be removed, so I can't insert for example a tag before and after the text.

Can I prevent this behaviour, or is there any workaround for this?

Upvotes: 1

Views: 2128

Answers (3)

Tim Down
Tim Down

Reputation: 324727

It's not inevitable that the selection is lost when the user clicks a button. The two ways I know to avoid it are:

  • Use the mousedown rather than the click event on the button and prevent the event's default action
  • Make the button unselectable.

See https://stackoverflow.com/a/11787147/96100.

Upvotes: 5

Balázs Varga
Balázs Varga

Reputation: 1856

I fixed it with saving the range variable into a window variable (global), after mouseup. Then use this to find and replace the elements. And it works!

I use this function to define whether a string is selected or not:

function isTextSelected(input) {
    var sel,range,selectedText;
    if(window.getSelection) {
        sel = window.getSelection();
        if(sel.rangeCount) {
            range = sel.getRangeAt(0);
            selectedText = range.toString();
            if(selectedText.length) {
                window._selection = range; // <-- This line saved my life! :)
                return true;
            }
        }
    }
}

And this is the code of the "B" button:

$('.editor-icon.b').click(function(e){
    var element = document.createElement('b');
    var selectedText = document.createTextNode(window._selection.toString());
    element.appendChild(selectedText);
    window._selection.deleteContents();
    window._selection.insertNode(element);
    window._selection = false;
});

Upvotes: 0

jleach
jleach

Reputation: 7800

I typically handle such cases by tracing the cursor change position within the editable control. Set up a variable to hold the last position, update it with each position change, then read the variable from your toolbar's event.

I don't work with JS enough to know the specific syntax for this offhand, but it's pretty general stuff for the most part.

Upvotes: 0

Related Questions