-5

What I'm trying to is:

  1. Pick up RGB value from an element
  2. Convert it to hex
  3. Put it into a text field

The first solution:

(taken from this thread RGB to Hex and Hex to RGB)

function rgbToHex(r, g, b) {
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

The problem is: it only returns #aN no matter what I feed it. Is the function flawed or am I doing something wrong?

See a demo here

The second solution:

From the same post as the upper mentioned.

function componentToHex(c) {
    var hex = c.toString(16);
    return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
    return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

This works if I pass the value to as numbers rgbToHex(255,255,255) but does nothing if I try to feed the numbers as a variable rgbToHex(rgbValue). (see the lines 19 to 25 in the demo)

See the demo here

All help appreciated :)

Community
  • 1
  • 1
any_h
  • 530
  • 3
  • 10
  • 27

1 Answers1

1

Try this:

function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

//Slap the rel values into the fields
$('.color').click(function(e) {
  e.preventDefault();  

  var rgbVal = $(this).attr('rel');

  var rgbValSplit = rgbVal.split(",");

  for (var i = 0; i < 3; i++) {
    if (!rgbValSplit[i]) {
      rgbValSplit[i] = 0;
    }
  }

  var finalHex = rgbToHex(+rgbValSplit[0], +rgbValSplit[1], +rgbValSplit[2]);

  $('.color-picker-rgb').val(rgbVal);
  $('.color-picker-hex').val(finalHex);

  $('body').css('background', finalHex);
});

http://codepen.io/anon/pen/eiqbz

The main problem was that you needed to pass 3 parameters like it expects. The other problem was that it was expecting numbers, not strings. So when you pass it "191", c.toString(16) will evaluate to just c. If you pass it a number, like 191, it will evaluate to the proper value.

Ian
  • 50,146
  • 13
  • 101
  • 111