Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContentEditable - Get current font color/size

I'm working on Rich Text Editor for web browser and I want to work with values of current font color and size in the RTE/ContentEditable element. Is there some preselected function to get these values, like execCommand, which is connected directly with ContentEditable element? Or should I use some text range jQuery library which will get these properties?

like image 977
optimista Avatar asked Jan 07 '12 13:01

optimista


1 Answers

You can use document.queryCommandValue() to get the colour and font size of the current selection in all major browsers:

Live demo: http://jsfiddle.net/timdown/AJBsY/

Code:

var colour = document.queryCommandValue("ForeColor");
var fontSize = document.queryCommandValue("FontSize");

However, the results are inconsistent across browsers and the FontSize command only works with font sizes 1-7 used in the HTML <font> element rather than CSS, so you'd be better off getting hold of the element containing the selection and examining its CSS properties using window.getComputedStyle() / currentStyle:

Live demo: http://jsfiddle.net/timdown/K4n2j/

Code:

function getComputedStyleProperty(el, propName) {
    if (window.getComputedStyle) {
        return window.getComputedStyle(el, null)[propName];
    } else if (el.currentStyle) {
        return el.currentStyle[propName];
    }
}

function reportColourAndFontSize() {
    var containerEl, sel;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            containerEl = sel.getRangeAt(0).commonAncestorContainer;
            // Make sure we have an element rather than a text node
            if (containerEl.nodeType == 3) {
                containerEl = containerEl.parentNode;
            }
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        containerEl = sel.createRange().parentElement();
    }

    if (containerEl) {
        var fontSize = getComputedStyleProperty(containerEl, "fontSize");
        var colour = getComputedStyleProperty(containerEl, "color");
        alert("Colour: " + colour + ", font size: " + fontSize);
    }
}

This is an improvement, but there are still browser inconsistencies such as differing units or colour formats.

like image 190
Tim Down Avatar answered Sep 20 '22 07:09

Tim Down