Home > other >  change view from list to grid after click
change view from list to grid after click

Time:01-18

I've created list view using bootstrap 5:

 <div >
    Click to switch to grid/list
    </div>

and here I've content list:

<div >
list view
...
.....
.......
</div>

and here I've content grid:

<div >
grid view
...
.....
.......
</div>

List view is enabled by default.

Can anyone help me if I click Click to switch to grid/list then remove tag from grid d-none and add d-none to tag list ?

and again when I click then rewrite changes ?

I try somelike this:

<button onclick="myFunction()">Click to switch to grid/list</button>

<script>
function myFunction() {
  document.getElementById("box").style.display = "none";
}
</script>

But this not work for me and I cannot get effect which I try and with this code not possible rewrite changes. I read every questions/answears here but none suit me and I can't implement it to my solution.

CodePudding user response:

This should work, it toggles the visibility between the two using style.display

    <button id="toggleButton">Toggle View</button>

    <div >
    list view
    ...
    .....
    .......
    </div>
    <div >
    grid view
    ...
    .....
    .......
    </div>        
    
    <script>
        const toggleButton = document.getElementById("toggleButton");
        const list = document.querySelector(".list");
        const grid = document.querySelector(".grid");
        grid.style.display = "none";
        toggleButton.addEventListener("click", function() {
        if (grid.style.display === "none") {
            grid.style.display = "block";
            list.style.display = "none";
        } else {
            grid.style.display = "none";
            list.style.display = "block";
        }
    });
    </script> 
  • Related