How To Get RGB Value From Hex Code In JavaScript

In this article, We will learn how to get RGB value from hex code in javascript

Step 1: Create html file and add following in it:

<html>

<head>
    <title>Hex To RGBA</title>
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>

<body>
    <div>
        <input type="text" id="hex" name="hex" />
        <button>Convert</button>
    </div>
    <div class="result"></div>
    <script type="text/javascript">
        var hex;
        $('button').click(function () {
            calc();
        });
        function calc() {
            var r, g, b, a = "";
            hex = $('input').val();
            if (hex == "") hex = "000000";
            if (hex.charAt(0) == "#") hex = hex.substring(1, hex.length);
            if (hex.length != 6 && hex.length != 8 && hex.length != 3) {
                alert("Please enter 6 digits color code !");
                return;
            }
            if (hex.length == 3) {
                r = hex.substring(0, 1);
                g = hex.substring(1, 2);
                b = hex.substring(2, 3);
                r = r + r;
                g = g + g;
                b = b + b;
            }
            else {
                r = hex.substring(0, 2);
                g = hex.substring(2, 4);
                b = hex.substring(4, 6);
            }
            if (hex.length == 8) {
                a = hex.substring(6, 8);
                a = (parseInt(a, 16) / 255.0).toFixed(2);
            }
            r = parseInt(r, 16);
            g = parseInt(g, 16);
            b = parseInt(b, 16);
            var css = "rgb(" + r + ", " + g + ", " + b + ")";
            if (hex.length == 8) css = "rgba(" + r + ", " + g + ", " + b + ", " + a + ")";
            $('.result').html('<span>' + css + '</span>');
            $('.result').css('border-top', 'solid 4px #' + hex);
        }
    </script>
</body>

</html>

Code In Action:

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories