Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Changing backround color using jquery

i am stuck in this challenge below.The challenge is from done the first part of it to change the div color randomly. but stuck in 2nd part (Then invert the DIVs background color using the function below, and use the inverted color for the font on that DIV.) What does it mean. Thanks

** Write jQuery code to loop over every DIV in any HTML document and give that DIV a random color background. Then invert the DIVs background color using the function below, and use the inverted color for the font on that DIV.

Test your code in Chrome console on many pages.

Here's the function to use for inverting colors: **

function invertColor(hexTripletColor) {
    var color = hexTripletColor;
    color = color.substring(1);           // remove #
    color = parseInt(color, 16);          // convert to integer
    color = 0xFFFFFF ^ color;             // invert three bytes
    color = color.toString(16);           // convert to hex
    color = ("000000" + color).slice(-6); // pad with leading zeros
    color = "#" + color;                  // prepend #
    return color;
}```

2 Answers

Hello Muhammad,

A solution to this could look something like this.

var colors = ['#000000', '#FF3516', '#34FF17', '#2458FF'];

function UpdateColors() {
    $('div').each(function(index) {
        var color = colors[Math.floor(Math.random() * colors.length)];
        var invertedColor = invertColor(color);
        $(this).css({
            'background-color': color,
            'color': invertedColor
        });
    });
}

Hope this helps.

Taylor

Hi Taylor. Thanks!