Sunday, February 9, 2014

RGB to hexa javascript convertor code

<script type="text/javascript" language="JavaScript">
        function hexToR(h) { return parseInt((cutHex(h)).substring(0, 2), 16) }
        function hexToG(h) { return parseInt((cutHex(h)).substring(2, 4), 16) }
        function hexToB(h) { return parseInt((cutHex(h)).substring(4, 6), 16) }
        function cutHex(h) { return (h.charAt(0) == "#") ? h.substring(1, 7) : h }
        function setColor (id, sColor) {
            var elem;
            if (document.getElementById) {
                if (elem = document.getElementById(id)) {
                    if (elem.style) { elem.style.backgroundColor = "#" + sColor; }  else {
                    }
                }
            }
        }
    </script>

<span id="colorSample" style="border: 1px solid gray;">                      </span>


<div>
<input type="text" name="hex" size="7" maxlength="7" value="FFFFFF">
<input type="button" name="btn" value="RGB"   onclick="setColor('colorSample',this.form.hex.value);
this.form.r.value=hexToR(this.form.hex.value);
this.form.g.value=hexToG(this.form.hex.value);
this.form.b.value=hexToB(this.form.hex.value);
">
        R:<input type="text" name="r" size="3" style="width: 33px;">
        G:<input type="text" name="g" size="3" style="width: 33px;">
        B:<input type="text" name="b" size="3" style="width: 33px;">

    </div>

No comments:

Post a Comment