blez's : blog

code / design / music and more


Leave a comment

How to get the system colors using JQuery?

Using CSS2 we can get the current system colors (the OS colors). Here‘s an article for that. CSS knows about the colors, but how can we use them from JavaScript? It’s tricky, because an element first needs to be created to know the actual color. Here’s a workaround that returns the color in hex format:

function GetSystemColor(name) {
    // create an invisible element, so we can get its color
    var el = $("<div style='display: none; color: " + name + "'></div>");
    $("body").append(el); // it must be appended to make css know the actual color
    var color = el.css('color');
    el.remove();
    
    // convert rgb to hex
    color = color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2).toUpperCase();
    }
    
    return "#" + hex(color[1]) + hex(color[2]) + hex(color[3]);
}
Advertisements