Wednesday, March 24, 2010

SharePoint jQuery: Setting View Column Width

A very common request for changes to SharePoint list views is how to set the column width. This is not possible to do using the ootb "List Settings", and the common suggested fix is to use SharePoint Designer (SPD) and convert the view into an "XSLT Data View": How can I manage columns widths in list views? Most large companies do, however, prevent the use of SPD.

With jQuery there is no need to use SPD or to convert the view. In the following example jQuery will change the width of the two columns "Status description" and "Type of Work" by changing their CSS style attribute.

Start by looking up the HTML markup for the two table headers using View-Source. I'm using jQuery filters that look for the TH elements using a CSS class selector and a content filter. Then add a Content Editor web-part (CEWP) to your page and enter this script in the source editor:

<!--ADJUST TABLE COLUMN WIDTH-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$("TH.ms-vh2-nograd:contains('Status description')").css("width", "150px");
$("TH.ms-vb:contains('Type of Work')").css("width", "150px");
});
</script>