Wednesday, June 6, 2012

Implementing jquery in SharePoint Web Part

Leave a Comment

JQuery is JavaScript library which comes with many in build methods.  To use jquery methods, it is mandatory to add jQuery to the page.  Once it is added on the page then selector can be wrapped with either $ or jQuery to make jquery object. 

We can add jquery.js by downloading from jquery.com  or giving web reference to various jquery CDN(Content delivery network).

Make sure you analyze all the cases if you deciding to add CDN reference to the page. Because it is hosted at web , which is all meant to be up 99% time but you never know when it goes down. So I will suggest to download jquery from http://www.jquery.com site and add reference to the page.

User can directly add jquery  in master page, page layouts or page  OR it could be added programmatically.

So before we start with the implementation lets take a case scenario : We want image scroller inside webpart.

For this i will refer SimplyScroll  JavaScript file  which can be download from here. http://logicbox.net/jquery/simplyscroll/

So lets implement this Step by Step

Step 1 : Create empty SharePoint project, because it will help to structure the solution and allow us to extend project with other SharePoint artifacts in future.


Step 2 : Add Layouts mapped folder to the Project. To create this right click VS project ->; Add ->  SharePoint Layouts mapped Folder.

Step 3:  Create Folder with name ImageScroller inside Layouts mapped Folder. One can directly add to the folder but too keep in structured way it is better to keep all custom artifacts in one Folder, so that it makes easier to locate file while trobuleshooting.

Step 4:   Download jquery file from jquery.com and add to the ImageScroller folder

Step 5:   Download simplyscroll plugin and add to the ImageScroller Folder

Step 6:  Create stylesheet file and add to the folder. Copy below stylesheet


.simply-scroll-container { 

    position: relative;

}

/* Clip DIV - automatically generated */

.simply-scroll-clip { 

    position: relative;

    overflow: hidden;

}

/* UL/OL/DIV - the element that simplyScroll is inited on

Class name automatically added to element */

.simply-scroll-list { 

    overflow: hidden;

    margin: 0;

    padding: 0;

    list-style: none;

}
  

.simply-scroll-list li {

    padding: 0;

    margin: 0;

    list-style: none;

}

    

.simply-scroll-list li img {

    border: none;

    display: block;

}

/* Custom class modifications - adds to / overrides above
.simply-scroll is default base class */
/* Container DIV */

.simply-scroll { 

    width: 576px;

    height: 200px;

    margin-bottom: 1em;

}
/* Clip DIV */

.simply-scroll .simply-scroll-clip {

    width: 576px;

    height: 200px;
}
/* Explicitly set height/width of each list item */    

.simply-scroll .simply-scroll-list li {

    float: left; /* Horizontal scroll only */

    width: 290px;

    height: 200px;
}


Step 6 :  Create new js file with name GetImages.js.

              Here curiously creating custom plugin to showcase how we can extend jquery by implementing new plugin.  To create plugin at javascript file to the ImageScroller Folder.

Add following code snippet 
        
(function ($) {
    $.fn.GetImages  = function () {
        return this.each(function () {
            $(this).simplyScroll();
        });
    };
})(jQuery);

To start creating plugin certain basic steps are needed to follow. Firstly warp the function with jQuery so that it can available if reference is added to the page.

New method is added by prefixing $.fn.  Here GetImages is new method .

Plugin execution starts with return this.each(function(){});  code block. Here we will bind simplyScroll plugin to the base selector i.e. this

Step 7 : Create a class to the project , let say UserImages.cs . This will hold user images struct objects. Structure objects are easily cleaned by Garbage Collector process so it is light weight then class.

public struct UserImages
  {
    public string ImageUrl;
    public UserImages(string imageUrl)
    {
      ImageUrl = imageUrl;
    }
  }

Step 8: Create a Picture Library to the SharePoint Site. Let say it "MyTeam". Add images to the library so that it could be used for the scroller.

Step 9 : Add Webpart to the project . Let say  ImageScrollerWebpart

Add following code blocks to the CreateChildControls method

Firstly add script and style reference to the page

Controls.Add(new ScriptLink() { Name = "/_layouts/ImageScroller/jquery-1.4.1.min.js" });

      Controls.Add(new ScriptLink()
                     {
                       Name = "/_layouts/ImageScroller/jquery.simplescroll.js"
                     });
      Controls.Add(new ScriptLink()
                     {
                       Name = "/_layouts/ImageScroller/GetPeoples.js"
                     });

      CssRegistration.Register("/_layouts/ImageScroller/scroll.css");
    

Create html structure

var div = new HtmlGenericControl("div");
      var ul = new HtmlGenericControl("ul id='scroller'");
      div.Controls.Add(ul);
      foreach (var userImages in GetUserImages())
      {
        var li = new HtmlGenericControl("li");
        li.Controls.Add(new HtmlImage { Src = userImages.ImageUrl,Height = 290 , Width = 200});
        ul.Controls.Add(li);
      }
      Controls.Add(div);

Add custom javascript file to the page to call GetPeoples.js plugin.

 
var script = new StringBuilder();
      script.Append("<script language='javascript'>");
      script.Append("$(document).ready(function(){");
      script.Append("$('#scroller').GetImages();");
      script.Append("});");
      script.Append("</script>");

      if (!Page.ClientScript.IsStartupScriptRegistered("GetPeopleScript"))
      {
        Page.ClientScript.RegisterStartupScript(GetType(), "GetPeopleScript", script.ToString());
      }

Here you will find a method GetUserImages() . This method will return userImages objects of all images to be referred in scroll webpart

  private List<UserImages> GetUserImages()
    {
      var images = new List();
      SPWeb web = SPContext.Current.Web;
      var userList = web.Lists["MyTeam"];

      foreach (SPListItem userItem in userList.Items)
      {
        images.Add(new UserImages{ ImageUrl = web.Url + "/" + userItem.File.Url});
      }
      return images;
    }

Deploy webpart and add ImageScrollerWebpart to the page. You will able to see images scrolling. You can also control other scrolling attributes. Visit http://logicbox.net/jquery/simplyscroll/ to see other options

Cheers !


0 comments: