4

I have the JavaScript for converting a HEX value to RGB but I was wondering if I could use jQuery to call the function and insert the HTML?

Here's the JavaScript;

function hex2rgb( colour ) {
    var r,g,b;
      if ( colour.charAt(0) == ‘#’ ) {
          colour = colour.substr(1);
    }

    r = colour.charAt(0) + ” + colour.charAt(1);
    g = colour.charAt(2) + ” + colour.charAt(3);
    b = colour.charAt(4) + ” + colour.charAt(5);

    r = parseInt( r,16 );
    g = parseInt( g,16 );
    b = parseInt( b ,16);
    return “rgb(” + r + “,” + g + “,” + b + “)”;
}

Update

I'm trying to have it so there is one input field where you type in a hex value, hit enter, and then the RGB value is inserted (maybe in a ghost element or something).

user1658756
  • 1,014
  • 5
  • 13
  • 27

3 Answers3

2

valid hex colors can have 3 or 6 characters after the '#'

function hexToRgb(hex){
    if(/^#([a-f0-9]{3}){1,2}$/.test(hex)){
        if(hex.length== 4){
            hex= '#'+[hex[1], hex[1], hex[2], hex[2], hex[3], hex[3]].join('');
        }
        var c= '0x'+hex.substring(1);
        return 'rgb('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+')';
    }
}
kennebec
  • 102,654
  • 32
  • 106
  • 127
1

HTML:

<input type="text" id="hex-input" placeholder="hex goes here"/>
<button id="magic-button">PUSH ME!</button>
<div id="rgb-output"></div>​​​​​​​​​​​​

JS:

$(document).ready(function() {
    $("#magic-button").click(function() {
        $("#rgb-output").html(hex2rgb($("#hex-input").val()));
    });

    $("#hex-input").keyup(function(event){
        if(event.keyCode == 13){
            $("#magic-button").click();
        }
    });
});

function hex2rgb( colour ) {
    var r,g,b;
    if ( colour.charAt(0) == '#' ) {
        colour = colour.substr(1);
    }
    if ( colour.length == 3 ) {
        colour = colour.substr(0,1) + colour.substr(0,1) + colour.substr(1,2) + colour.substr(1,2) + colour.substr(2,3) + colour.substr(2,3);
    }
    r = colour.charAt(0) + '' + colour.charAt(1);
    g = colour.charAt(2) + '' + colour.charAt(3);
    b = colour.charAt(4) + '' + colour.charAt(5);
    r = parseInt( r,16 );
    g = parseInt( g,16 );
    b = parseInt( b ,16);
    return 'rgb(' + r + ',' + g + ',' + b + ')';
}​    

http://jsfiddle.net/2fb3D/

st3inn
  • 1,556
  • 9
  • 17
-1

You can pass the elementId to the function

function hex2rgb( colour, id )
...
   $("#"+id).text("rgb(" + r + "," + g + "," + b + ")")
}
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176