Thursday, June 15, 2017

Expand the first group only on a SharePoint List View Web Part (SharePoint 2013)

If you add as SharePoint list view web part to a SharePoint page using SharePoint designer, you are given the ability to sort, group and filter the results of that web part for display.  If you choose to group by a specific element, then you can decide to either expand or contract all groups by default. Handy.

However, if you want to expand just the first grouping, and have the rest of the groups collapsed, there is no default setting to allow that to occur.  I have taken the original blog post posted here:

Original Blog Post

and have updated it for SharePoint 2013.

The original idea used here is sound, locate and click, using javascript and jquery, the plus sign located next to the first group.  However, using the web part ID did not work in my case, so I had to dig a bit deeper.

Here is the code I used to call the function:

<script type="text/javascript">

$(document).ready(function() {

And here is the slightly modified function:

function collapseGroups() {
   var closestElement = document.getElementById('group0');
   var myimg = closestElement.getElementsByTagName('img')[0];
   var mysrc = myimg.src;


The challenging part of getting this working is identifying the document element that is closest to the + sign.  The original post used the name of the web part that hosts the list data, however, this did not work in my case.  Instead, it clicked the first columns sort header in the web part, and resorted the list by that column on page load!

So the approach is fine, click the + sign once you find it, we just need to find an element deeper in the list view web part.  Here is how I did it.

Navigate to your web part page and make note of the Group Header for your grouped column.  So if you were grouping by "Course Year", then "Course Year" would be what you are looking for.

Open the page in source view, and search for your grouping column name. When I searched for "Course Year" I got back html that looked like this:

<tr id="group0">
<td colspan="100" nowrap class="ms-gb">
<a href="javascript:" onclick="javascript:ExpCollGroup('0-1_', 'img_0-1_',event, true);return false;">
<img src="/_layouts/15/images/plus.gif" border="0" alt="expand" id="img_0-1_">&nbsp;Course Year</a>

You can see the plus image markup, plus javascript event associated with that markup that fires the button clicked event.  Unfortunately, between page refreshes, the image id changes, so I couldn't use that. 

However, the closest element with an ID was the table row (tr) that wrapped this line.  This tr has an ID of "group0".  I used this ID value in the collapse groups function, and it worked!  And it appears to be a more stable name than the ever changing values of the + image. 

No comments:

Post a Comment