In my recent post I wrote about a solution that enables users to resize the column width of SharePoint views. In this post I provide a sample for configuring the width of the columns through a helper list.
I’ve created a custom list called ColumnWidths and added a string (ColumnName) and a numeric field (ColumnWidth) to it for the name and the desired column width of the field. Note, that you should use the same name for the field, as it is referred to in the view / HTML source, for example, a title with context menu is called LinkTitle. The Title field of the configuration list item contains the site relative URL of the view that we would like to customize.
The script is based on jQuery and the same LINQ for JavaScript (ver.3.0.3-Beta4) library that I used in these samples as well. The script was injected to the target view page (for example into the /Lists/Test/AllItems.aspx) through the Content Editor Web Part.
In this case I used REST to query the configuration list, a similar result could be achieved through the ECMAScript Client Object Model.
- <script src="/_layouts/jQuery/jquery-1.8.3.min.js"></script>
- <script src="/_layouts/jQuery/linq.js"></script>
- <script src="/_layouts/jQuery/linq.jquery.js"></script>
- <script language="ecmascript" type="text/ecmascript">
- $(document).ready(startScript);
- function startScript() {
- var pageUrl = document.URL;
- var pageUrlLenght = pageUrl.length;
- var siteUrl = ctx.HttpRoot;
- var siteUrlLength = siteUrl.length;
- var siteRelativeUrl = pageUrl.substring(siteUrlLength, pageUrlLenght);
- var url = siteRelativeUrl.substring(0, siteRelativeUrl.lastIndexOf("?"));
- $.ajax({
- type: 'GET',
- contentType: 'application/json;odata=verbose',
- url: siteUrl + "/_vti_bin/listdata.svc/ColumnWidths()?$filter=Title eq '/Lists/Test/AllItems.aspx'&$select=ColumnName,ColumnWidth",
- headers: {
- "Accept": "application/json; odata=verbose"
- },
- dataType: "json",
- complete: function (result) {
- var response = JSON.parse(result.responseText);
- if (response.error) {
- alert("Error: " + response.error.code + "\n" + response.error.message.value);
- }
- else {
- var columnWidths = response.d.results;
- Enumerable.from(columnWidths).forEach(function(x) {
- $('div.ms-vh-div[name="' + x.ColumnName + '"]').closest('th').width(x.ColumnWidth);
- });
- }
- },
- error: function(xmlHttpRequest, textStatus, errorThrown) {
- alert(errorThrown);
- }
- });
- }
- </script>
Here is the original formatting of our Test list view. This is the same output as the view is displayed before the script is executed:
And here is the view after the page is loaded completely and the script is executed:
Through this method the width of the columns can be relative easily configured without using SharePoint Designer.
