Switch Grid and List View Using jQuery

In this tutorial we are going to see how to switch Grid and List view using jquery. This example will help you to understand easily how to create grid/list view in html using jquery. This concept is generally used in e-commerce website where you can see product in Grid and list view both by single click on button.

Have a look how to create list view and grid view in html using jquery.

Show and Hide Password Field with jQuery and JavaScript

Switch Grid and List View Using jQuery

HTML

<div id="container">
       <span class="switcher grid">Grid View</span>
        <span class="switcher list">List View</span>
        <hr>

   <ul class="list">
        <li>Box 1</li>
        <li>Box 2</li>
        <li>Box 3</li>
        <li>Box 4</li>
        <li>Box 5</li>
        <li>Box 6</li>
        <li>Box 7</li>
        <li>Box 8</li>
        <li>Box 9</li>
        <li>Box 10</li>
    </ul>
</div>    

jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){ 

$('.switcher').on("click",function(){ 

if($(this).hasClass('list')){
$('#container ul').removeClass('grid');
$('#container ul').addClass('list');
}

if($(this).hasClass('grid')){
$('#container ul').removeClass('list');
$('#container ul').addClass('grid');
}
});
});

</script>

CSS

.switcher
{
width:85px;
height:35px;
padding:10px;
margin:3px;
color:#fff;
background:#325980;
}
li
{
background: #1a3e19;
margin:10px;
color:#fff;
padding:10px;
}
.list li
{
width:100%;
list-style: none;
}

.grid li
{
 display:block;
 width:25%;
 display: inline-block;
}

Live DemoDownload Script

Leave a Comment