To display large number of data we prefer to use Treeview. Let’s take an example where we want to show all those countries & their respective states where we have our customers. In the below jQuery Treeview example I implemented the Same. This Treeview is simply created using Jquery. Using this Treeview you can show any level of data in hierarchy manner.
Jquery is an advanced programming language. For a Jquery professional it is very simple to create a Treeview. Look at the example below here I used only 5 to 6 lines of codes to create a Treeview. The logic I implemented here is so straight forward. In HTML I have ul & li elements which represents data for my Treeview. UL elements inside li elements are sub nodes. Using Jquery document.ready method initially I am tracking all the li elements & inside the li elements which ul elements length is greater than zero I am adding a class “node” for them.
Then in the next loop I am detecting the li elements with class “node” and for their anchor tags click event binding toggle class “active”. To show the expand & collapsible feature smooth I used slideToggle with slow.
JQuery Treeview Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>JQuery Treeview example</title> <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script> <script type="text/javascript"> $(document).ready(function() { $('.treeview li').each(function() { if($(this).children('ul').length > 0) { $(this).addClass('node'); } }); $('.treeview li.node > a').click(function() { $(this).parent().toggleClass('active'); $(this).parent().children('ul').slideToggle('slow'); }); }); </script> </head> <body> <div class="treeview"> <ul> <li><a href="#">Pakistan</a> <ul> <li><a href="#">Faisalabad</a></li> <li><a href="#">Karachi</a></li> <li><a href="#">Gujranwala</a></li> </ul> </li> <li><a href="#">India</a> <ul> <li><a href="#">Odisha</a> <ul> <li><a href="#">Bhubaneswar</a></li> <li><a href="#">Cuttuck</a></li> <li><a href="#">Balasore</a> <ul> <li><a href="#">Balasore Golei</a></li> <li><a href="#">MPC College Road</a></li> <li><a href="#">FM University Road</a></li> </ul> </li> </ul> </li> <li><a href="#">West Bengal</a></li> </ul> </li> <li><a href="#">Nepal</a> <ul> <li><a href="#">Kathmandu</a></li> <li><a href="#">Bharatpur</a></li> </ul> </li> </ul> </div> </body> </html>
Treeview CSS Styles for Ul li elements
ul, #myUL { list-style-type: none; } #myUL { margin: 0px; padding: 0px; } .box { cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .box::before { content: "10"; color: black; display: inline-block; margin-right: 7px; } .check-box::before { content: "11"; color: lightblue; } .nested { display: none; } .active { display: block; }