-2

I have a template with multiples class using one color, can I dynamically change that color to another using javascript?

When the page loads, locate all the div, span, p, h, with color #512a69 and change it to #ef7e8e.

Is it possible?

Thanks.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
David
  • 15
  • 5

1 Answers1

0

Here is a solution which I'll explain step-by-step.

First, call colorReplace("#512a69", "#ef7e8e");. The first value is the target color, and the second is the replacement color.

Inside it, $('*').map(function(i, el) { will select all tags in the DOM tree. For each element, its getComputedStyle(el) styles array is returned. You can customize the selector for faster processing (e.g. $('div').map(function(i, el)) {).

All style attributes containing "color" (e.g. background-color, -moz-outline-color, etc.), it will be checked if the color value is equal to your target color. If so, it will be replaced with the target color.

Colors are returned like rgba(0,0,0,0) or rgb(0,0,0), not like #FFFFFF, so a quick conversion is done from rgb to hex for the comparison. That uses the internal rgb2hex() function.

I hope this is what you are looking for.


function colorReplace(findHexColor, replaceWith) {
    // Convert rgb color strings to hex
    // REF: https://stackoverflow.com/a/3627747/1938889
    function rgb2hex(rgb) {
        if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;
        rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

        function hex(x) {
            return ("0" + parseInt(x).toString(16)).slice(-2);
        }
        return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }

    // Select and run a map function on every tag
    $('*').map(function(i, el) {
        // Get the computed styles of each tag
        var styles = window.getComputedStyle(el);

        // Go through each computed style and search for "color"
        Object.keys(styles).reduce(function(acc, k) {
            var name = styles[k];
            var value = styles.getPropertyValue(name);
            if (value !== null && name.indexOf("color") >= 0) {
                // Convert the rgb color to hex and compare with the target color
                if (value.indexOf("rgb(") >= 0 && rgb2hex(value) === findHexColor) {
                    // Replace the color on this found color attribute
                    $(el).css(name, replaceWith);
                }
            }
        });
    });
}

// Call like this for each color attribute you want to replace
colorReplace("#512a69", "#ef7e8e");

Source: https://stackoverflow.com/a/30724171/1136132

idnovate
  • 992
  • 1
  • 5
  • 10