Tuesday, March 10, 2009

Minimize WebParts with jQuery


Recently I had to implement a quick way for the users to minimize and restore webparts with a single click, rather than having to use the default webpart verb to Minimize / Restore: it involves two clicks and it’s not very intuitive for the users.
My solution is the following  jQuery script:
$(document).ready(function()
{
    //display the hand cursor over the title table rows for each webpart and hook to the "onclick" event
    $("tr.ms-WPHeader").css("cursor", "pointer").css("cursor", "hand").bind("click", function ()
    {
        //get the div element nesting the webpart contents: the navigation is based on standard webpart rendering behaviour
        var divElement = $(this).parents('tr:first').siblings('tr:first').children('td:first').children('div:first');     
        //and togle its visibility status 
        divElement.toggle();
    }
    );
}
);
When triggered in the master page, a page layout or even from within the default Content Editor WebPart, this script will enable toggling the visibility of the webparts on the page with a single click on their title. It also works when the default chrome state is minimized, bypassing the default behaviour.
On a side note, I think it would be great to see more out-of-the-box jQuery action in the next version of SharePoint, now that it officially supported in Visual Studio 2010.