Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //https://stackoverflow.com/questions/70491148/how-to-inverse-font-color-based-on-cells-background-color-in-google-apps-script
- //https://stackoverflow.com/a/70491346/10789707
- function onEdit(e) {
- r = e.range;
- if(r.getSheet().getSheetName() == "colors"){ //the sheet I want to apply this to is called colors
- var rows = r.getNumRows();
- var columns = r.getNumColumns();
- var colors = [] //this is our 2 dimensional array of colors in case you copy and paste a large amount of colors
- for (var i = 1; i <= rows; i++) { //go down each row
- var row = [] //create a new row array to clear the old one when we go down a row
- for (var j = 1; j <= columns; j++) { //then go across each column
- row.push(r.getCell(i,j).getValue()) //put together the row of colors
- }
- colors.push(row); //insert our row of colors so we can go down the next row
- }
- const fontColor = lum([111, 22, 255]);
- const fontColorsRow = new Array(columns).fill(fontColor);
- const fontColors = new Array(rows).fill(fontColorsRow);
- r.setBackgrounds(colors) //batch update in case you update many colors in one copy and paste otherwise it will be very slow
- r.setFontColors(fontColors);
- }
- }
- function lum(rgb) {
- var lrgb = [];
- rgb.forEach(function(c) {
- c = c / 255.0;
- if (c <= 0.03928) {
- c = c / 12.92;
- } else {
- c = Math.pow((c + 0.055) / 1.055, 2.4);
- }
- lrgb.push(c);
- });
- var lum = 0.2126 * lrgb[0] + 0.7152 * lrgb[1] + 0.0722 * lrgb[2];
- return (lum > 0.179) ? '#000000' : '#ffffff';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement