0

I am working on a script that converts rgb into hexidecimal color code. However it is only converting the first two characters and then throwing a NaN error for the rest.

Here is what i have:

    function convert(r, g, b) {
        return toHex(r) + toHex(g) + toHex(b);
    }

    function toHex(c) {
        c = parseInt(c);
        return "0123456789abcdef".charAt((c - c % 16) / 16) + "0123456789abcdef".charAt(c % 16);
    }

    function getStyle(id) {
        var elem = document.getElementById(id);
        var style = window.getComputedStyle(elem, null).getPropertyValue('background-color');
        var clear = style.replace(/[rgb\()]/g, '');
        document.write(clear);
        document.getElementById(id).innerHTML = '<span>#' + convert(clear) + '</span>';
    }

    getStyle('box1');
    getStyle('box2');
    getStyle('box3');
    getStyle('box4');

When i type convert(13, 49, 96) it converts it correctly, it doesn't work how i have it setup. Can anyone offer some insight?

EDIT

Here is the css i am using:

    #box1 {background-color:#0d3160;}
    #box2 {background-color:#ffffff;}
    #box3 {background-color:#ecebe3;}
    #box4 {background-color:#242e35;}

Here are the RGB values

rgb(13, 49, 96)
rgb(255, 255, 255)
rgb(236, 235, 227)
rgb(36, 46, 53)
Geoffrey
  • 457
  • 5
  • 21
  • Can you please post some of your sample inputs for toHex()? – Erik May 15 '15 at 17:02
  • I updated the post. Let me know if that isn't what you are looking for. – Geoffrey May 15 '15 at 17:04
  • check here, http://jsfiddle.net/Mottie/xcqpF/1/light/ and here, http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb – carlos a. May 15 '15 at 17:06
  • When you do your `document.write(clear);` what is the output? If it's a string like "1,2,3" then that's part of the problem. When you call your convert function, you're passing it one value (the string), but it wants three. – Mike Willis May 15 '15 at 17:08
  • Thanks carlos, that was a much simpler way of doing it. – Geoffrey May 15 '15 at 17:09

1 Answers1

2

You are passing a string to the function, you need to convert it into an array and pass each element into the function Convert:

function getStyle(id) {
    var elem = document.getElementById(id);
    var style = window.getComputedStyle(elem, null).getPropertyValue('background-color');
    var clear = style.replace(/[rgb\()]/g, '');

    document.write(clear);
    document.getElementById(id).innerHTML = '<span>#' + convert.apply(this,clear.split(',')) + '</span>';
}

The change comes in with

convert.apply(this,clear.split(','))

where you convert the variable clear into an array of numbers then pass those as arguments into the function convert.

Rolyataylor2
  • 201
  • 1
  • 5