markasoftware
markasoftware

Reputation: 12672

Stop clicking on text from cancelling selection

I'm trying to make a simple rich text editor, and I'm getting stuck at the stupidest thing. For the bold buttons, instead of having a button, I'm trying to make it so that, near the top of the screen, there are several spans, and each one has a thing you can do to the text, such as bold, italic, underline, etc, and when you click on one I want it to toggle if the selected text in the contenteditable div is bold, italic, or underline. Basically, instead of buttons, I want to simply click on a span to toggle those things.

So I put a whole bunch of spans in the right place and put event handlers on them that did the appropriate execCommand. However, when the user clicks on the spans, it cancels the selection in the contenteditable div, so that the execCommand doesn't do anything. I tried setting the css user-select to none (I also used prefixes), cancelling the selectstart event, cancelling the click event, but it still cancels the selection when I click on it

You can see the jsfiddle here

I don't want to use a button instead of a span or anything. I don't want to do it in a hacky way (such as copying the selection on input, and then recreating the selection after the click) either

Upvotes: 3

Views: 70

Answers (1)

plalx
plalx

Reputation: 43728

There's a few ways to achieve this. You can prevent the default mousedown behaviour like below:

document.getElementById('bold').addEventListener('mousedown', function (e) {
    e.preventDefault();
});

FIDDLE

You can also just use the semantically correct elements such as <button> rather than <span>. If you do not like the way <button> element looks by default just re-style it.

FIDDLE

Upvotes: 4

Related Questions