Snippets Collections
// html
 <div id="app">
      <div class="grid-container">
        <div class="box"><a href="#">remove</a></div>
        <div class="box"><a href="#">remove</a></div>
        <div class="box"><a href="#">remove</a></div>
        <div class="box"><a href="#">remove</a></div>
      </div>
    </div>


//css


.grid-container {
  background-color: aliceblue;
  width: 100%;
  min-height: 200px;
  display: grid;
  column-gap: 1rem;
  grid-template-columns: repeat(
    var(--col-grid-count, 4),
    var(--col-make-width, 1fr)
  );
}

.box {
  width: 100%;
  height: 100%;
  background-color: firebrick;
  padding-top: 1rem;
}

.box a {
  text-align: center;
  margin-top: 1rem;
  color: white;
  display: flex;
  justify-content: center;
  cursor: pointer;
  text-decoration: none;
}


//js

(function () {
  "use strict";

  const gridContainer = document.querySelector(".grid-container");

  if (!gridContainer) return;

  function changeItemWith(value) {
    gridContainer.style.setProperty("--col-make-width", value);
  }

  function updateGrid(number) {
    const updatedBoxes = document.querySelectorAll(".box").length;
    gridContainer.style.setProperty("--col-grid-count", updatedBoxes);

    const widthOptions = {
      1: () => changeItemWith("minmax(230px, 250px)"),
      2: () => changeItemWith("minmax(295px, 320px)"),
      3: () => changeItemWith("minmax(245px, 420px)"),
      4: () => changeItemWith("minmax(243px, 500px)"),
    };

    console.log(`Number of boxes: ${number}`);
    console.log(`Function in widthOptions:`, widthOptions[number]);

    // Fix: Call the function if it exists, otherwise apply default width
    // see note on how widthOptions[number](); works
    if (widthOptions[number]) {
      widthOptions[number]();
    } else {
      changeItemWith("205px"); // Default case
    }
  }

  function onHandleLink(event) {
    event.preventDefault();

    const link = event.currentTarget;
    const box = link.parentElement;

    if (box) {
      box.remove();
      // Fix: Pass the correct length
      updateGrid(document.querySelectorAll(".box").length); 
    }

    console.log(box);
  }

  function listeners() {
    document.querySelectorAll(".box").forEach((box) => {
      const link = box.querySelector("a");
      if (link) {
        link.addEventListener("click", onHandleLink);
      }
    });
  }

  function init() {
    // Fix: Pass the correct length
    updateGrid(document.querySelectorAll(".box").length); 
    listeners();
  }

  init();
})();



/*
NOTE; Understanding widthOptions 

widthOptions is an object where each key (like 1, 2, etc.) maps to a function:

const widthOptions = {
  1: () => changeItemWith("minmax(230px, 250px)"),
  2: () => changeItemWith("minmax(295px, 249px)"),
  3: () => changeItemWith("minmax(245px, 1fr)"),
  4: () => changeItemWith("minmax(243px, 1fr)"),
};

Each value is an anonymous function (() => {}) that calls changeItemWith(...).


Accessing a Function in an Object
If number is 1, then: widthOptions[1]

is the same as: () => changeItemWith("minmax(230px, 250px)");
which in the widthOptions object is:  1: () => changeItemWith("minmax(230px, 250px)")


So if we call it with (), it executes:
widthOptions[1]();
*/ 

// See codesandbox for my implementation
// https://codesandbox.io/p/sandbox/q3926h?file=%2Fsrc%2Findex.mjs%3A28%2C6-28%2C30
/**
We want to change the grid repeat() depending on the items in a grid
where repeat(4, 1fr) are dynamic values we can change in JS using setProperty()
note: setProperty(property-name, value)
*/
 
// our html = we add a data-grid attribure to show the grid number
<div class="qld-compare_page__courses" data-grid></div>
 
// our css
.courses{
  	//repeat(4, 1fr); replace with 2 new css variables, and a fallback
  	// in this case var(--compare-col-count) has a fallback of 4 
   repeat(var(--compare-col-count, 4), var(--compare-col-width, 205px));
}
 
// JS function



// create the changeGrid function outside the main function below
   function changeGrid(value){
       parentGrid.style.setProperty("--compare-col-width", value);
    }
       
 
function adjustGrid(number) { // number will the dynamic value that changes
  	// get the parent to which the grid willl be appplied
    const parentGrid = document.querySelector(".qld-compare_page__courses");
 
 	 // if element exists
     if (parentGrid) { 
      // set the grid attribute in the html to the number value in the param
      parentGrid.dataset.grid = `courses-${number}`; 
	  // now we are using the set Property to get the var give it the number value
      parentGrid.style.setProperty("--compare-col-count", number);
 
       /**
       switch (number) { // if numbers 1, 2, 3 or 4 is reached then do your thing!
            case 1:
           // here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 230px)");
            break;
           
            case 2:
			// here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 249px)");
            break;
 
            case 3:
			// here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 1fr)");
            break;
 
           	case 4:
			// here we are using setProperty() to target that css var, and apply value
         	parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 1fr)");
            break;
           
                default:
                parentGrid.style.setProperty("--compare-col-width", "205px");
                break;
            }
        }
       */
       
       
       /**
       1. create object with all options
       2. create a function to call inside the object
       3. The function returns the code want to repeat with params
       4. Call that function using the object[dynamic] number
       */ 
       
       
       // Note we are still using number from the main function as this is the value
	  // that will output 1, 2, 3, 4
       
       const options = {
         // use cases here for key value pairs
				 1: () => changeGrid("minmax(205px, 230px)"),
                2: () => changeGrid("minmax(205px, 249px)"),
                3: () => changeGrid("minmax(205px, 1fr)"),
                4: () => changeGrid("minmax(205px, 1fr)"),
       }
      
       
       // call it
       // param should be the dynamic value of the oject and the matching number param
       changeGrid(options[number]) 
       
       
       
    }
 
 
 
	//use local storage for the  number we want
  adjustGrid(JSON.parse(localStorage.getItem("courses") || "[]").length);
 
 
 
 


// here is the full JS code with CSS variables
	

    function cssColWidthVariable(value) {
        const parentGrid = document.querySelector(".qld-compare_page__courses");
        parentGrid.style.setProperty("--compare-col-width", value);
    }

  
    function adjustGrid(number) {
        const parentGrid = document.querySelector(".qld-compare_page__courses");
        if (parentGrid) {
            parentGrid.dataset.grid = `courses-${number}`;
            parentGrid.style.setProperty("--compare-col-count", number);

            const gridOptions = {
                1: () => cssColWidthVariable("minmax(205px, 230px)"),
                2: () => cssColWidthVariable("minmax(205px, 249px)"),
                3: () => cssColWidthVariable("minmax(205px, 1fr)"),
                4: () => cssColWidthVariable("minmax(205px, 1fr)"),
            };

            cssColWidthVariable(gridOptions[number] || "205px");
        }
    }

   
  
// call the function based on a changing number
adjustGrid(JSON.parse(localStorage.getItem("courses") || "[]").length);
        


/**
We want to change the grid repeat() depending on the items in a grid
where repeat(4, 1fr) are dynamic values we can change in JS using setProperty()
note: setProperty(property-name, value)
*/

// our html = we add a data-grid attribure to show the grid number
<div class="qld-compare_page__courses" data-grid></div>

// our css
.courses{
  	//repeat(4, 1fr); replace with 2 new css variables, and a fallback
  	// in this case var(--compare-col-count) has a fallback of 4 
   repeat(var(--compare-col-count, 4), var(--compare-col-width, 205px));
}

// JS function

function adjustGrid(number) { // number will the dynamic value that changes
  	// get the parent to which the grid willl be appplied
    const parentGrid = document.querySelector(".qld-compare_page__courses");

 	 // if element exists
     if (parentGrid) { 
      // set the grid attribute in the html to the number value in the param
      parentGrid.dataset.grid = `courses-${number}`; 
	  // now we are using the set Property to get the var give it the number value
      parentGrid.style.setProperty("--compare-col-count", number);

       switch (number) { // if numbers 1, 2, 3 or 4 is reached then do your thing!
            case 1:
           // here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 230px)");
            break;
           
            case 2:
			// here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 249px)");
            break;

            case 3:
			// here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 1fr)");
            break;

           	case 4:
			// here we are using setProperty() to target that css var, and apply value
         	parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 1fr)");
            break;
           
                default:
                parentGrid.style.setProperty("--compare-col-width", "205px");
                break;
            }
        }
    }



	//use local storage for the  number we want
  adjustGrid(JSON.parse(localStorage.getItem("courses") || "[]").length);




// the css starter
// note we are resetting the --compare-col-count
 &__courses {
      display: grid;
      grid-template-columns: clamp(120px, 39vw, 180px) repeat(var(--compare-col-count, 4), var(--compare-col-width, 205px));
      grid-template-rows: repeat(2, 1fr) repeat(6, 90px) repeat(1, 1fr);
      z-index: 1;
      column-gap: 1.6rem;


// NEXT SEE: CONVERT setProperty with CSS variables to object and functions
star

Thu Feb 20 2025 02:48:38 GMT+0000 (Coordinated Universal Time)

#setproperty #cssvariables
star

Thu Feb 20 2025 00:46:19 GMT+0000 (Coordinated Universal Time)

#setproperty #cssvariables

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension