/**
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