Second Life of a Hungarian SharePoint Geek

May 27, 2013

Creating resizable Columns in SharePoint Views

Filed under: jQuery, SP 2010, Views — Tags: , , — Peter Holpar @ 22:44

Recently I was experimenting with solutions that would enable users to resize the width of the columns of a SharePoint view. As you might know, SharePoint calculates the width of columns automatically, and the result is not always optimal. Although it’s relative easy to set the width using SharePoint Designer I was looking for a method that one can use through the web UI, without any external applications.

One of the methods I’ve tried out was to attach a keyboard event handler to the div element of the field header caption. I chose the div, and not the parent th element, because other event handlers were already registered for th, and I didn’t want to interfere with them. When the field caption has the focus (see image below), and the user presses Shift + Left arrow keys, the width of the column is decreased. When the user presses Shift + Right arrow keys, the width of the column is increased.

image

I used jQuery and the following script (injected through the Content Editor Web Part into the view page) to achieve the goal:

Code Snippet
  1. <script src=”/_layouts/jQuery/jquery-1.8.3.min.js”></script>
  2. <script language=”ecmascript” type=”text/ecmascript”>
  3. $(document).ready(startScript);
  4. function startScript() {
  5.     $(‘div.ms-vh-div’).keydown(function (e) {
  6.         if (e.keyCode != 16) {
  7.             var widthChange = 20;
  8.             var th = $(e.srcElement).closest(‘th’);
  9.             var widthTh = $(th).width();
  10.             if (e.keyCode == 37) {
  11.                 $(th).width(widthTh – widthChange);
  12.             }
  13.             else if (e.keyCode == 39) {
  14.                 $(th).width(widthTh + widthChange);
  15.             }
  16.         }
  17.     });
  18. }
  19. </script>

The result was quite promising, however it has a definitive shortage as well: the settings are not persisted, so the user has to repeat the resizing each time. Theoretically we could store the customized widths in cookies or in SharePoint lists (per user), and reapply the settings on each page load.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: