Skip to content

Instantly share code, notes, and snippets.

@slaffko1
Created June 17, 2021 10:23
Show Gist options
  • Save slaffko1/4962b081602845808a8ee63f96e97fe2 to your computer and use it in GitHub Desktop.
Save slaffko1/4962b081602845808a8ee63f96e97fe2 to your computer and use it in GitHub Desktop.
RGBA to HEX alpha
window.setTimeout(function () {
$(function () {
$("#converter").submit(function(){return false;});
$("#rgba").bind('keyup change', function () {
var value = $(this).val();
setHex(value);
});
$("#hex").bind('keyup change', function () {
var value = $(this).val();
setRgba(value);
});
setHex = function(val) {
var valArr = val.split("(")[1].split(")")[0].split(","),
red = toHex(valArr[0]),
green = toHex(valArr[1]),
blue = toHex(valArr[2]),
alpha = toHex(valArr[3]*256) || 00;
$("#hex").val("#" + red + green + blue + alpha);
};
setRgba = function(val) {
var value = val.substring(1,9),
red = parseInt(value.substring(0,2), 16),
green = parseInt(value.substring(2,4), 16),
blue = parseInt(value.substring(4,6), 16),
alpha = Math.round((parseInt(value.substring(6,8), 16)/255)*100)/100;
$("#rgba").val("rgba(" + red + "," + green + "," + blue + "," + alpha +")");
};
toHex = function(val) {
val = parseInt(val);
val = Math.max(0,val);
val = Math.min(val,255);
val = Math.ceil(val);
return "0123456789ABCDEF".charAt((val-val%16)/16) + "0123456789ABCDEF".charAt(val%16);
};
});
}, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment