DEV Community

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

How To Create List And Grid View Using JavaScript

In this example, we will see how to create a list and grid view using javascript. many times clients have requirements like a toggle between list and grid view. So, for list view and grid view in HTML, we are using a piece of HTML, CSS, and jquery.

here I will give you an example list and grid view using jquery. So, copy the below code and get the output of the list and grid view example in javascript.

In this example, I have created one file and added HTML code CSS code, and javascript.

Create HTML file

Create an HTML file and the below code in your file.

<div id="container">
<center><h1>
How To Create List And Grid View Using JavaScript - Techsolutionstuff
</h1><br>
    <div class="buttons">
        <button class="grid">Grid View</button>
        <button class="list">List View</button>
        </div></center>

    <ul class="list">
        <li style="background:lightgray">Item 1</li>
        <li>Item 2</li>
        <li style="background:lightgray">Item 3</li>
        <li >Item 4</li>
        <li style="background:lightgray">Item 5</li>
        <li>Item 6</li>

    </ul>
</div>
Enter fullscreen mode Exit fullscreen mode

Read Also : StartOf And EndOf Functions Example Of Carbon

Add CSS

Now, add some CSS for list view and grid view.

h1 {font-size:22px; margin-top:20px;}

.grid, .list {padding:15px;}

#container ul { list-style: none; }

#container .buttons { margin-bottom: 20px; }

#container .list li { width: 100%; border-bottom: 1px; margin-top:5px; margin-bottom: 5px; padding: 5px; }

#container .grid li { float: left; width: 20%; height: 50px; border: 1px solid #CCC; padding: 20px; }
Enter fullscreen mode Exit fullscreen mode

Add JavaScript

In this step, we are adding some javascript for change list and grid view.

$('button').on('click',function(e) {
    if ($(this).hasClass('grid')) {
        $('#container ul').removeClass('list').addClass('grid');
    }
    else if($(this).hasClass('list')) {
        $('#container ul').removeClass('grid').addClass('list');
    }
});
Enter fullscreen mode Exit fullscreen mode

And finally, you will get output like the below image.

how_to_create_list_and_grid_view_using_javascript_output


You might also like :

Top comments (0)