Showing posts with label rgb. Show all posts
Showing posts with label rgb. Show all posts

Saturday, May 16, 2015

Convert RGB Values Of A Color To A Hexadecimal String And Vice Versa Using jQuery

Hex: RGB:
RGB: Hex:


/* RGB Value To Hexa Decimal */
function toHex(n) {
     n = parseInt(n);
     if (isNaN(n)) return "00";
     n = Math.max(0,Math.min(n,255));
     return "0123456789ABCDEF".charAt((n-n%16)/16)
     + "0123456789ABCDEF".charAt(n%16);
}
toHex("20");

/* Hext Decimal Value To RGB Value */
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}
var str = "#34F355";
hexToR(str);
hexToG(str);
hexToB(str);