Skip to content

Instantly share code, notes, and snippets.

@kozo002
Created October 3, 2013 07:38
Show Gist options
  • Save kozo002/6806421 to your computer and use it in GitHub Desktop.
Save kozo002/6806421 to your computer and use it in GitHub Desktop.
Get brightness from background color with jQuery
jQuery.fn.brightness = function() {
var bg_color, rgba, y;
bg_color = this.css('background-color');
if ((bg_color != null) && bg_color.length) {
rgba = bg_color.match(/^rgb(?:a)?\(([0-9]{1,3}),\s([0-9]{1,3}),\s([0-9]{1,3})(?:,\s)?([0-9]{1,3})?\)$/);
if (rgba != null) {
if (rgba[4] === '0') {
if (this.parent().length) return this.parent().brightness();
} else {
y = 2.99 * rgba[1] + 5.87 * rgba[2] + 1.14 * rgba[3];
if (y >= 1275) {
return 'light';
} else {
return 'dark';
}
}
}
} else {
if (this.parent().length) return this.parent().brightness();
}
};
@kozo002
Copy link
Author

kozo002 commented Oct 3, 2013

Usage: jQuery('.your-html-element').brightness(); // => return 'light' or 'dark' or undefined

@xem
Copy link

xem commented Oct 8, 2013

Where do the numbers come from?

@OwlyCode
Copy link

OwlyCode commented Oct 8, 2013

Even its not the exact values it might be related to this http://en.wikipedia.org/wiki/Luminance_(relative). The general idea is that green impacts us the most on the perception of what is "bright".

@wooorm
Copy link

wooorm commented Oct 8, 2013

The Y in YIQ.

@ezebra
Copy link

ezebra commented Apr 26, 2017

Hi, may I use this gist in a project? I couldn't find any licensing information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment