Change grid layout on mouse click

Is it possible to change grid layout on mouse click? For example, if I have a grid layout of three rows and I want to have an event listener that when click the grid layout will change from three rows to three columns.

Yes it is possible. You would simply need to adjust the styling on the grid layout to accommodate your layout needs. I also believe it’s possible to add a transition from grid-template-rows to columns. Do you have any code you could share?

1 Like
.gridcontainer {
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  justify-content: center;
}

.gridcontainer {
  display: grid;
  grid-template-columns: 1fr 4fr 1fr;
  justify-content: center;
}

<div class="gridcontainer">
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
</div>

i want the grid layout to change from three rows to three columns if any of the item is click.

i think i can do this with react. with mouse event. is that fine? or using html and css the only way i know to do that is hover effect , is that what you are looking for? how to create mouse event without java sript

You want to change the CSS of an element I did’nt test but I will look something like this

$(".item").addEventListener("click",function(){
    $(".gridcontainer").css("display","grid").css("grid-template-rows","1fr 1fr 1fr");
});

Okay if I’m understand correctly this might be what you want.

The css:

.gridcontainer {
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  justify-content: center;
}

The javascript:

  const gridContainer = document.querySelector('.gridcontainer')
  const gridItems = document.querySelectorAll('.item')

  // loop over each grid item and add an event listener
  gridItems.forEach(item => item.addEventListener('click', () => {
    gridContainer.style.gridTemplateColumns = '1fr 1fr 1fr'
  }))

Thanks guys assistance

@camperextraordinaire Thanks heaps.