1

I have this DIV and I want to select some text then, when pressing on some button, apply the bold style to it.

<div id="editor" contenteditable="true"></div>
<input type="button" id="bold" value="B" />

My JavaScript "works" like this

function CaretPosition(dom) {
    var caretPos = 0, containerEl = null, sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            if (range.commonAncestorContainer.parentNode == dom) {
                caretPos = range.endOffset;
            }
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        if (range.parentElement() == dom) {
            var tempEl = document.createElement("span");
            dom.insertBefore(tempEl, dom.firstChild);
            var tempRange = range.duplicate();
            tempRange.moveToElementText(tempEl);
            tempRange.setEndPoint("EndToEnd", range);
            caretPos = tempRange.text.length;
        }
    }
    return caretPos;
}

function SelectText(dom, start, end) {
    var sel, range;
    if (window.getSelection && document.createRange) {
        range = document.createRange();
        range.setStart(dom.firstChild, start);
        range.setEnd(dom.lastChild, end);
        sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(dom);
        range.select();
    }
}

var cp = 0;
var sp;

document.getElementById('editor').onkeyup = function() {
    cp = CaretPosition(document.getElementById('editor'));
    sp = window.getSelection().getRangeAt(0);
}

document.getElementById('editor').onmouseup = function() {
    cp = CaretPosition(document.getElementById('editor'));
    sp = window.getSelection().getRangeAt(0);
}

document.getElementById('bold').onclick = function() {
    document.getElementById('editor').focus();
    SelectText(document.getElementById('editor'), cp, sp);
    document.execCommand('bold', false, null);
}

Well, this code doesn't work and I'm trying to understand what could be wrong. I want it to be cross-browser. I think the problem lies in the setStart and setEnd arguments. Can anyone give me some clues?

EXPECTED RESULT When I select some portion of text and click on the BOLD button, the selected text should change to bold.

ACTUAL RESULT Looks like the SelectText() function doesn't select the text correctly, so when execCommand is called, it doesn't change the selected text. It changes other section of the text. It's like I don't send the correct start and end values, or something might be wrong with the dom.firstChild/dom.lastChild. If I do this in my SelectText() function (change start by 2 and end by 6):

function SelectText(dom, start, end) {
    var sel, range;
    if (window.getSelection && document.createRange) {
        range = document.createRange();
        range.setStart(dom.firstChild, 2);
        range.setEnd(dom.lastChild, 6);
        sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(dom);
        range.select();
    }
}

then, when I click once the text inside the DIV, from char 2 to 6 is selected and changed. When I click again, chars from 2 to 8 are selected and changed, and so on.

UPDATE My last code can be tested at http://jsfiddle.net/wjjvH/15/

I managed to make it work on IE but not on other browsers. Also, I don't know how to find out the selection start and end so I can send them to the SelectText function.

5
  • What is it that doesn't work? What is the expected result, and what is the actual result?
    – Jay
    Sep 16, 2012 at 5:03
  • I updaed my question to answer yours, thanks.
    – ali
    Sep 16, 2012 at 9:48
  • The main problem is that, when you click (mouse is down) on anything other than editor, the focus is lost as well as the current selection. Thus, getSelection in the SelectText function will always return as no selection. You should save the current selection object to a global variable and use that instead of getSelection.
    – Jay
    Sep 16, 2012 at 22:11
  • I updated my question. I could do that but it looks like the global variable selection empty itself when editor is unfocused. I posted my ode on jsfiddle: jsfiddle.net/wjjvH/15
    – ali
    Sep 17, 2012 at 17:02
  • 1
    You can use mousedown instead of click and prevent the browser's default action (i.e. nicking the focus) by adding return false: jsfiddle.net/timdown/wjjvH/16
    – Tim Down
    Sep 17, 2012 at 22:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.