views:

39

answers:

1

Hi

I am trying to identify whether a selected text (in Firefox) is bold or not? For e.g.:

<p>Some <b>text is typed</b> here</p>

<p>Some <span style="font-weight: bold">more text is typed</span> here</p>

The user can either select a part of bold text, or the full bold text. Here is what I am trying to do:

function isSelectedBold(){
    var r = window.getSelection().getRangeAt(0);
    // then what?
}

Could you please help me?

Thanks
Srikanth

A: 

If the selection is within an editable element or document, this is simple:

function selectionIsBold() {
    var isBold = false;
    if (document.queryCommandState) {
        isBold = document.queryCommandState("bold");
    }
    return isBold;
}

Otherwise, it's a little trickier: in non-IE browsers, you'll have to temporarily make the document editable:

function selectionIsBold() {
    var range, isBold = false;
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel && sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            document.designMode = "on";
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
    if (document.queryCommandState) {
        isBold = document.queryCommandState("bold");
    }
    if (document.designMode == "on") {
        document.designMode = "off";
    }
    return isBold;
}
Tim Down
Thank you so much. I will settle with this workaround for now.
Srikanth Vittal