Convert RGB to Hexadecimal with Javascript

Asked

Viewed 683 times

2

I have to convert rgb value to Hex when moving inputs(range), but when I move nothing happens, the hexadecimal color should appear below also as the color is changed above.

The color is loaded only when the page loads, when I move the ranges nothing happens.

Follows code: https://codepen.io/fmm312/pen/zWKYyX

  • If the answer helped and/or is correct, mark as correct to help other people who have the same problem.

1 answer

5

One way to do this is with the following functions:

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);
}

alert(rgbToHex(0, 51, 255)); // #0033ff

For more information, visit this link.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.