1

I made a JSFiddle of a HEX to RGB conversion but I'm wondering how I can do it the other way (RGB to HEX).

$('#hex').bind('blur keydown', function (event) {
  setTimeout(function () {
    var rgb = [],
        broken = false,
        value = $("#hex").val(),
        hex = (value+'').replace(/#/, '');

    if (value.length === 1 && value !== '#') {
      $("#hex").val(value);
    }

    if (hex.length == 3) hex = hex + hex;
    for (var i = 0; i < 6; i+=2) {
      rgb.push(parseInt(hex.substr(i,2),16));
      broken = broken || rgb[rgb.length - 1].toString() === 'NaN';
    }

    $('#rgb').val(broken ? '' : 'rgb(' + rgb.join(',') + ')');   
  }, 13);
});

'#hex' and '#rgb' are just inputs:

<input type="text" id="hex" placeholder="hex">
<input type="text" id="rgb" placeholder="rgb">

Here's the JSFiddle.

I'm also wondering why if I was to replace broken with false, I get an error. Do you know why I can't remove var broken = false and just replace with false?

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
user2203362
  • 259
  • 1
  • 7
  • 11

1 Answers1

0

Here is a code that will convert RGB to HEX:

$(function(){
  var $hex = $('#hex');
  $('#rgb').on('keyup blur', function() {
    var value = this.value,
        rgb,
        hex = '',
        component,
        i;
    try {
      if(value && value.indexOf('rgb(') === 0 && value[value.length-1] === ')') {
        rgb = value.slice(4,-1).split(',');
        if(rgb.length === 3) {
          for(i=0;i<3;i++) {
            if(rgb[i] <= 0xFF) {
              component = parseInt(rgb[i],10);
              if(isNaN(component)) {
                throw new SyntaxError();
              }
              component = component.toString(16);
              if(component.length === 1) {
                component = '0'+component;
              }
              hex += component;
            } else {
              throw new RangeError();
            }
          }
          $hex.val('#'+hex);
        } else {
          throw new SyntaxError();
        }
      }
    } catch(e) {
      $hex.val('');
    }
  });
});

An here is working example http://jsbin.com/amisen/3/edit

Vadim
  • 8,701
  • 4
  • 43
  • 50
  • It works perfectly, thanks! Do you know what the problem is with my HEX to RGB? Apparently the logic is wrong. – user2203362 Apr 06 '13 at 13:26
  • @user2203362 You should replace `if (hex.length == 3) hex = hex + hex;` with `if (hex.length === 3) hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];` – Vadim Apr 06 '13 at 13:32
  • In the RGB to HEX, is there a way it can display the shorter version e.g. `#444` instead of `#444444` or is that not possible? – user2203362 Apr 06 '13 at 15:18