How to use:
1st: Make sure jQuery is included in your code
2nd:Include the script where in your code after jQuery has been included.
3rd: $('#colorful-element').parentHasLightBgColor();
| /** | |
| * This function is used to check if an element's parent div has a light "background color" (or "background"). | |
| * | |
| * This is an adaptation of the larryfox's code: https://gist.github.com/larryfox/1636338. | |
| **/ | |
| (function($){ | |
| $.fn.parentHasLightBgColor = function(){ | |
| var r, g, b, hsp, | |
| parentBgColor = this.parent().css('background-color'); | |
| if(parentBgColor) { | |
| if (parentBgColor.match(/^rgb/)) { | |
| parentBgColor = parentBgColor.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/); | |
| r = parentBgColor[1]; | |
| g = parentBgColor[2]; | |
| b = parentBgColor[3]; | |
| } else { | |
| /* use Jed's alg for gathering the backgroud of the parent element: | |
| http://gist.github.com/983661*/ | |
| parentBgColor = +("0x" + parentBgColor.slice(1).replace( | |
| parentBgColor.length < 5 && /./g, '$&$&') | |
| ); | |
| // extract the r, g, and b values from the parent element's background color | |
| r = parentBgColor >> 16; | |
| g = parentBgColor & 255; | |
| b = parentBgColor >> 8 & 255; | |
| } | |
| // Use the HSP equation from http://alienryderflex.com/hsp.html | |
| hsp = Math.sqrt( | |
| 0.299 * (r * r) + | |
| 0.587 * (g * g) + | |
| 0.114 * (b * b) | |
| ); | |
| /*use the hsp from above to check if the parent element | |
| has a light or dark background color*/ | |
| if (hsp > 127.5) { | |
| //the parent of this element is light | |
| return true; | |
| } else { | |
| //the parent of this element is dark | |
| return false; | |
| } | |
| } | |
| //return -1 so the default can be handled appropriately | |
| return -1; | |
| } | |
| })(jQuery); |
| DO WHATEVER YOU WANT TO PUBLIC LICENSE | |
| Version 2, December 2004 | |
| Copyright (C) 2016 Lincoln W Daniel <http://lincolnwdaniel.com> | |
| Everyone is permitted to copy and distribute verbatim or modified | |
| copies of this license document, and changing it is allowed as long | |
| as the name is changed. |