Advertisement
Guest User

How to inverse font color based on cell's background Color in Google Apps Script?

a guest
Dec 27th, 2021
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //https://stackoverflow.com/questions/70491148/how-to-inverse-font-color-based-on-cells-background-color-in-google-apps-script
  2. //https://stackoverflow.com/a/70491346/10789707
  3.  
  4. function onEdit(e) {
  5.   r = e.range;
  6.  
  7.   if(r.getSheet().getSheetName() == "colors"){ //the sheet I want to apply this to is called colors
  8.     var rows = r.getNumRows();
  9.     var columns = r.getNumColumns();
  10.     var colors =  [] //this is our 2 dimensional array of colors in case you copy and paste a large amount of colors
  11.  
  12.     for (var i = 1; i <= rows; i++) { //go down each row
  13.       var row = [] //create a new row array to clear the old one when we go down a row
  14.       for (var j = 1; j <= columns; j++) { //then go across each column
  15.         row.push(r.getCell(i,j).getValue()) //put together the row of colors
  16.       }
  17.       colors.push(row); //insert our row of colors so we can go down the next row
  18.     }
  19.    
  20.     const fontColor = lum([111, 22, 255]);
  21.     const fontColorsRow = new Array(columns).fill(fontColor);
  22.     const fontColors = new Array(rows).fill(fontColorsRow);
  23.    
  24.     r.setBackgrounds(colors) //batch update in case you update many colors in one copy and paste otherwise it will be very slow
  25.    
  26.     r.setFontColors(fontColors);
  27.   }
  28. }
  29.  
  30. function lum(rgb) {
  31.     var lrgb = [];
  32.     rgb.forEach(function(c) {
  33.         c = c / 255.0;
  34.         if (c <= 0.03928) {
  35.             c = c / 12.92;
  36.         } else {
  37.             c = Math.pow((c + 0.055) / 1.055, 2.4);
  38.         }
  39.         lrgb.push(c);
  40.     });
  41.     var lum = 0.2126 * lrgb[0] + 0.7152 * lrgb[1] + 0.0722 * lrgb[2];
  42.     return (lum > 0.179) ? '#000000' : '#ffffff';
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement