Monday, May 7, 2012

Integrating jQuery Timeago plugin in SharePoint 2010


I've been doing lots of reading about all the nifty things that can be done using jQuery on a SharePoint site. jQuery is one of the most popular javascript libraries used by ASP.NET developers.  There are many interesting jQuery plugins. Timeago is one of my favourite plugin which makes it easy to support automatically updating fuzzy timestamps like in Facebook, Twitter etc.
While working on a POC I need to display dates in content query webpart like in facebook / twitter (a min ago, 2 days ago etc).
Mark Rackley has written excellent posts (A Dummies Guide to SharePoint and jQuery–Getting Started) on jQuery and SharePoint.
To integrate Timeago jquery plugin to your Sharepoint 2010 site follow these steps.


1. Upload the jQuery and Timeago plugin to Site Assets document library.
2. Write your script, references the appropriate libraries, save it as a file and upload it to Site Assets document library
 <script src="../SiteAssets/jquery.min.js"></script>  
 <script src="../SiteAssets/jquery.timeago.js"></script>  
 <script type="text/javascript">  
      jQuery(document).ready(function($) {  
           jQuery(".timeago").timeago();  
      });  
 </script>  

3. Put a content editor web part on the page and link to the script (CustomJs.js) in Site Assets document library. This content editor web part is used to link the scrips uploaded in step 1 to the current page.


          4. Put a Content Query Web part on the page and configure it as shown in below screen shots.


    5. Open the ItemStyle.xsl from Style Library. Change the ItemStyle to include the [title] attribute and also change the div class from “description” to “timeago” as shown below. For POC i have used the Description column to display the Modified date. You can create your custom column and use it in CQWP.
 <div class="timeago">  
          <xsl:attribute name="title">  
            <xsl:value-of select="@Description" />  
           </xsl:attribute>  
           <xsl:value-of select="@Description" />  
         </div>  

              

6. Save the XSL and refresh the page.
You will see the date strings are replaced with the time delta.



Happy scripting :)

Note: SPUtility.TimeDeltaAsString Method can be also used to show the time difference between two time value as String.

4 comments:

  1. Nice and descriptive post Hemant.
    We are waiting for more to come.

    ReplyDelete
  2. For displaying announcements we use XSLT and i need to show date in time ago format.
    my question is :
    if i create a calculated column in announcement list and after that can i use this time ago format plugin for that calculated column??

    ReplyDelete
  3. Hi Sachin,
    Yes, You can use the timeago plugin on the calculated column

    Regards,
    Hemant

    ReplyDelete

Thanks for your Comment.

There was an error in this gadget