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

Graham Patrick
Graham Patrick
8,294 Points

Average of two hex colors gives the same result

Hey Guys

I'm trying to get the average of two hex colors in Javascript and I keep hitting the same result and get a return value of #000000

any ideas?

 const color1 = document.getElementById('Number1');
    const color2 = document.getElementById('Number2');

    // get the average color of two hex colors.
    function average(color1,color2){

        const avg  = function(a,b){ return (a+b)/2; };
        const t16  = function(c){ return parseInt((''+c).replace('#',''),16) };
        const hex  = function(c){ const t = (c>>0).toString(16);

        return t.length === 2 ? t : '0' + t },

            hex1 = t16(color1),
            hex2 = t16(color2),

            r    = function(hex){ return hex >> 16 & 0xFF},
            g    = function(hex){ return hex >> 8 & 0xFF},
            b    = function(hex){ return hex & 0xFF},

            output  = '#' + hex(avg(r(hex1),r(hex2)))
                + hex(avg(g(hex1),g(hex2)))
                + hex(avg(b(hex1),b(hex2)));

        console.log(output);


        document.getElementById('output').innerHTML=output ;
    }

1 Answer

Steven Parker
Steven Parker
231,269 Points

The code here seems OK, but this code only defines the function.

Perhaps the problem is in the code where the function is called, or where the values to be passed to it are acquired.