šŸ“• Build AI Agents using LangGraph.js is now out!

CSS Grid to List view toggle

Let's see how to create a toggle button to display items in a grid or a simple one-column list. We will use just simple vanilla JavaScript and CSS Grid.

We will build the below example:

component example that changes its layout from CSS Grid to List

Using buttons we will toggle between the following:

  • a single-column list
  • a 2-column CSS Grid layout
  • a 3-column layout
  • a multi-column list where we will try to fit as many items as possible.

You can get creative and add or remove as many options as you need for the number of columns.

This is the starting markup for the grid:

<div id="main" class="container">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>

Toggling between grid view and list view is really only a matter of styling. What we need to do is to add a bit of JavaScript to add or remove classes:

const removeGridClasses = (container)=> {
    container.classList.remove(
        'grid-2-col', 
        'grid-3-col', 
        'grid-n-col'
    )
}
const setGridColumns = (num)=> {
    const container = document.getElementById("main")
    removeGridClasses(container)
    if (num !== 0) container.classList.add(`grid-${num}-col`)
}

The setGridColumns() will be called by each button with different parameters:

<button onclick="setGridColumns(0)">☰ List</button>
<button onclick="setGridColumns(2)">☷ Grid 2 columns</button>
<button onclick="setGridColumns(3)">☷ Grid 3 columns</button>
<button onclick="setGridColumns('n')">ā–¦ Multi columns</button>

And the final pice of the puzzle is the CSS classes:

.container { 
    &.grid-2-col {
        display: grid;
        grid-template-columns: 1fr 1fr;
    }

    &.grid-3-col {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
    }

    &.grid-n-col {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));

    }
}

You can see the full code here and you can play with the live example on GitHub pages.

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


Leave a Reply

Your email address will not be published. Required fields are marked *