Tuesday, June 19, 2012

Expanding/Collapsing Web Parts

The problem:

My requirements state that a certain web part on my page should be expandable/collapsible. When the user presses the "-" sign this web part is to collapse, whereas when she presses the "+" sign this web part is to expand. When the page first loads, this web part should be collapsed.

The solution:

We should use jQuery for this purpose. First, we need to find out the ID of the web part in question (it should start with "MSOZoneCell_", something like "MSO_ZoneCell_WebPartctl00_m_MyCoolWebPart") - view your web part page in the source and find the ID there.

Then, add a new Content Editor Web Part to your page. In the CEWP, in the HTML source, type this:

<div align="right" class="content" id="jLoadDiv"><a href="javascript:show(&#39;MSOZoneCell_WebPartctl00_m_MyCoolWebPart&#39;);"><img title="Show" id="plus" alt="Show" src="/_layouts/images/EXPAND.GIF"/></a> <a href="javascript:hide(&#39;MSOZoneCell_WebPartctl00_m_MyCoolWebPart&#39;);"><img title="Hide" id="minus" alt="Hide" src="/_layouts/images/COLLAPSE.GIF" style="display: none"/></a> </div>
<script type="text/javascript">

$("document").ready(function()
{
$('td[id*="MSOZoneCell_WebPartctl00_m_MyCoolWebPart"]').css("display", "none");
$('img[id*="minus"]').css("display", "none");
});
function show(webpartID)
{
$('td[id*="'+webpartID+'"]').css("display", "block");
$('img[id*="plus"]').css("display", "none");
$('img[id*="minus"]').css("display", "block");
}
function hide(webpartID)
{
$('td[id*="'+webpartID+'"]').css("display", "none");
$('img[id*="minus"]').css("display", "none");
$('img[id*="plus"]').css("display", "block");
}</script>

Make sure you set the Chrome to None on your CEWP.

That's it. This does the job. You can even export the CEWP and then add its contents (with the contents of the Content element being HTML-encoded - use  this tool to perform the encoding) to the page or elements file.

No comments:

Post a Comment