DotNetCurry Logo

jQuery TreeView with Expand Collapse Icons

Posted by: Suprotim Agarwal , on 10/14/2015, in Category jQuery and ASP.NET
Views: 24874
Abstract: Create a Nested TreeView in jQuery which auto collapses and comes with Expand Collapse Icons

In my previous article Auto Collapsible Nested TreeView using jQuery, I showed you how to create a Nested TreeView using jQuery with the following features:

  • Auto collapse the tree with animation when it is loaded
  • Expand and collapse nodes with animation when they are clicked
  • Prevent Hyperlinks inside the list from expanding/collapsing nodes

 

This TreeView works just fine, but there’s a UI enhancement that’s needed. For eg: if a user were to look at the treeview, she/he should be able to determine which nodes can be expanded. That’s not very clear in our TreeView. What we need is an automated way to add expand and collapse icons to any parent that has a child node. These icons should be toggled automatically as the nodes are clicked. So when the TreeView loads, we should see the following:

s5-treeview-expand

Similarly when the user expands any of the nodes, the icon should be swapped to the following:

s5-treeview-collapse

Observe how the icons are toggling from a collapsed state (-) to an expanded state (+).

I grabbed a nice set of expand-collapse icons from www.shapes4free.com . It’s a nice site to get icons/buttons/design elements for free. The icons are available as png’s and psd’s.

Let’s get started. Create a new file called ‘ExpandCollapseIconsTree.html’ folder. The markup remains the same as what we saw in our previous article.

Add the following CSS in the expandcollapse.css file kept in the css folder:

.icon { 
    background: 
        transparent 
        url( /images/plus-minus.png )
        no-repeat left top; 
    display:block; 
    height:12px;
    width:12px; 
    float:left;
    cursor:pointer;
}

.plus { 
    background-position: left top; 
    margin-top:3px;
}

.minus { 
    background-position: left -10px;
    margin-top:3px;
}

The plus-minus.png is a CSS image sprite that contains both the expand(+) and collapse(-) icons. We are using .plus and .minus to position the expand and collapse icons.

 

Initially we start by displaying the ‘+’ icon. The code changes required to make use of these icons are as follows:

$('#Decor ul')
    .hide(400)
    .parent()
    .prepend('');

The first step is to collapse the tree and add a before each textnode using prepend().

The next step is to expand the treeview when the user clicks on the (+) icon and toggle it to (-). We should be able to expand and collapse both on the click of the icon, as well as on clicking the textnode. Here’s the code for it.

$('#Decor li').on('click', function (e) {
    e.stopPropagation();
    $(this).children('ul').slideToggle('slow', function () {
        if ($(e.target).is("span")) {
            $(e.target)
                .toggleClass('minus', $(this).is(':visible'));                        
        }
        else
        {
            $(e.target).children('span')
                .toggleClass('minus', $(this).is(':visible'));                        
        }
    });
});

Here slideToggle is used to reveal or conceal list items. As I mentioned earlier, the user should be able to expand and collapse the nodes both on the click of the span (icon), as well as on clicking the textnode. So here using if..else, we check to see if the item clicked (e.target) was a span (icon) or the entire

  • node. If it is a
  • node, run the ‘else’ block and search for the children('span') inside it and run the toggleClass() on it.

    We are using toggleClass( className, switch ) here. The switch is a Boolean value to determine whether the class should be added or removed. This value is determined using $(this).is(':visible') expression. So when the node is expanded, $(this).is(':visible') expression results in true, hence the minus class is added and you see the collapse (-) sign. Similarly when the node is collapsed, the expression results in false, hence the minus class is removed and you see the expand(+) sign.

    View the page in the browser and you can now expand and collapse the nodes using (+) and (-) icons respectively.

    Live Demo: http://www.jquerycookbook.com/demos/S5-MenusTreeViews/48-ExpandCollapseIconsTree.html

    Download the entire source code of this article (Github)

    Was this article worth reading? Share it with fellow developers too. Thanks!
    Share on Google+
  • Further Reading - Articles You May Like!
    Author
    Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

    Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

    Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



    Page copy protected against web site content infringement 	by Copyscape




    Feedback - Leave us some adulation, criticism and everything in between!