jQuery.fn.darken = function() {
$(this).each(function() {
var darkenPercent = 15; // darken color by 15 percent
var rgb = $(this).css('background-color');
rgb = rgb.replace('rgb(', '').replace(')', '').split(',');
var red = $.trim(rgb[0]);
var green = $.trim(rgb[1]);
var blue = $.trim(rgb[2]);
// darken
red = parseInt(red * (100 - darkenPercent) / 100);
green = parseInt(green * (100 - darkenPercent) / 100);
blue = parseInt(blue * (100 - darkenPercent) / 100);
// lighten
/* red = parseInt(red * (100 + darkenPercent) / 100);
green = parseInt(green * (100 + darkenPercent) / 100);
blue = parseInt(blue * (100 + darkenPercent) / 100); */
rgb = 'rgb(' + red + ', ' + green + ', ' + blue + ')';
$(this).css('background-color', rgb);
});
return this;
}
$('table tr td').darken(); // run the above plugin on all table cells
jQuery Darken the background color of an element
Can also be used to lighten an element's background color simply by uncommenting the "lighten" lines, then commenting the "darken" lines.
Snippet Viewed 15324 times.
Share your jQuery code snippets:
- Get some recognition & a link back to your site.
- Create your own code library.
- Help your fellow developers, as they have helped you.
Related Articles