I'm trying to create some jQuery function that changes object bgcolor to lighter or darker (you set parameter as difference of tone of color). And as I think it should work, but it cracks.
$.fn.changeBg = function(difference){
var hexToRgb = function(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
var rgbToHex = function(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
//returns color n-tones lighter or darker (for negavitve values) from given.
var changeColor = function(hex,tones){
var rgb = hexToRgb(hex);
rgb.r+=tones;
rgb.g+=tones;
rgb.b+=tones;
rgb.r=rgb.r>255?255:rgb.r;
rgb.r=rgb.r<0?0:rgb.r;
rgb.g=rgb.g>255?255:rgb.g;
rgb.g=rgb.g<0?0:rgb.g;
rgb.b=rgb.b>255?255:rgb.b;
rgb.b=rgb.b<0?0:rgb.b;
var hex = rgbToHex( rgb.r , rgb.g , rgb.b );
return hex;
}
var bgColor = $(this).css('background-color');
var secColor = changeColor(bgColor,difference);
$(this).css('background-color',secColor);
}
Fiddle - any idea what is wrong with that?
console.log(hex, result);
just after you're calling.exec()
. – Andreas