Skip Ribbon Commands
Skip to main content

:

> Posts > A Dummies Guide to SharePoint & jQuery – An Easy to Use Content Slider
January 30
A Dummies Guide to SharePoint & jQuery – An Easy to Use Content Slider

So, in my last post we learned how to read SharePoint list data using SPServices:

    A Dummies Guide to SharePoint & jQuery - Reading List Data With SPServices

Now, let's add to that and create something useful. Let's use the data we read in that blog post and create a Content Slider with it. Sound like a plan?

If you are lazy like I am, and lack creativity like I do, then third party jQuery libraries nicely help mask both of these traits. However finding the right jQuery library that works nicely with SharePoint can sometimes be tricky.

Tips for finding the right jQuery library and integrating it into SharePoint

As an extra added bonus (and at no additional charge), before we jump in and talk about the library I chose to use for the content slider allow me to give you some tips about finding the right jQuery library and integrating it into SharePoint.

Never underestimate the advantage of a well maintained library

It's always a good sign for a library when it is actively maintained; it means you're more likely to get support if you have problems or questions. It also means you'll generally be able to get your hands on documentation to help you take full advantage of what the library can do. Conversely, a library without support or documentation may have hidden pitfalls that you are unaware of until you are well past the point of no return.

Test on your target browsers

There are a lot of cool jQuery libraries out there for doing charts, graphs, calendars, animations, and pretty much anything else you can think of. However, check to make sure it works for your target browser. Many libraries use styles that look bad or flat out don't work in IE. Also, if you throw IE6 into the mix your choices fall dramatically. But really, if you are worried about IE6 you have far bigger problems than finding a good jQuery library. J Regardless, before you even download a library to play with it, make sure it works on the browsers you will be using.     

Duplicate the file structure

So, do you have a separate document library for scripts, style sheets, and images? Well… I hope you are flexible about that, at last during development. Many jQuery libraries rely on a style sheets and images all working together under some predetermined directory structure. If you separate these files into different document libraries you are making your life more difficult than it has to be. If you are dead set on all the files being in a different file structure then you might invest many hours only to discover that the library does not work in SharePoint for some other reason.

Make sure it works vanilla / be wary of styles

Which brings me to my final point, before you go to the time and effort to fully implement a jQuery library in SharePoint make sure you can at least get the library to work in SharePoint using one of the various examples that the library hopefully has provided for you. It is all too common for a jQuery library to commandeer styles that SharePoint relies on; often making your SharePoint site completely unusable. Sometimes these styles can be fixed with a couple of small tweaks, and other times it could take hours depending on the library.

Our library of choice: Awkward Showcase - http://showcase.awkwardgroup.com/

Why did I choose this library over others? Well, its transition effects look good in IE, it's got good documentation, it's free, and most importantly it works well with SharePoint. The only downside is that it does not look like the developers are actively supporting it anymore? Bummer… but other than that I've been very impressed.

So, download the library files and let's get started.

The files

First thing we need to do is upload the Awkward Showcase files to our SiteAssets document library. Again, to make our life easier, we are going to create a "css" folder and an "images" folder to hold all of the necessary files. For my purposes I need the following files:

/SiteAssets/jquery.aw-showcase.min.js
/SiteAssets/css/style.css

I also uploaded all the images the library uses even though I may not need them all now:

/SiteAssets/images/arrows.png
/SiteAssets/images/arrows-small.png
/SiteAssets/images/black-opacity-40.png
/SiteAssets/images/ black-opacity-40.png
/SiteAssets/images/ black-opacity-60.png
/SiteAssets/images/ black-opacity-80.png
/SiteAssets/images/plus.png
/SiteAssets/images/white-opacity-40.png
/SiteAssets/images/ white-opacity-60.png
/SiteAssets/images/ white-opacity-80.png

The tweaking

So, remember how I said the style sheets can sometimes interfere with SharePoint? Well, this library is no different in that respect. Fortunately, all I had to do was delete the first 56 lines of the style sheet. So, go ahead and do that as well.

You will also need to go through and tweak the style sheet for the dimensions of your content slider. When things don't line up quite right, arrows don't show up, or something else is off, the first place to look is the style sheet.

The Script

Now that we have our library and all supporting files in place, and removed some of the unwanted style sheet entries, it's time to write our script to implement the content slider in SharePoint. To accomplish this I'm going modify the script we used in the previous blog post (again that was A Dummies Guide to SharePoint & jQuery - Reading List Data With SPServices ).

As a refresher, this script reads the Name, Blog, and Picture for a speaker from my SharePoint List "Speakers". It then just dumps that information out in a very simple table. Basically all we have to do to make this script work for our content slider is:

  1. Add the proper references for the Awkward Showcase files
  2. Instead of having a table as a container for our speaker data, create a div that is needed by the content slider
  3. Instead of appending rows to a table with our speaker information, append divs to our content slider main div
  4. Apply the Content Slider library to the main Content Slider div.

It actually turns out to be a very painless process. Our script ends up looking like the script below. 

<script type="text/javascript" src="../SiteAssets/jquery.min.js"></script>
<script type="text/javascript" src="../SiteAssets/jquery.SPServices.min.js"></script>
<script type="text/javascript" src="../SiteAssets/jquery.aw-showcase.min.js"></script>

<link rel="stylesheet" href="../SiteAssets/css/style.css" />

<script type="text/javascript">


//this is where the script starts after the page is loaded
$(document).ready(function() { 

    GetSpeakers();

});

function GetSpeakers()
{
        //The Web Service method we are calling, to read list items we use 'GetListItems'
        var method = "GetListItems";
        
        //The display name of the list we are reading data from
        var list = "Speakers";

        //We need to identify the fields we want to return. In this instance, we want the Name (Title),
        //Blog, and Picture fields from the Speakers list. You can see here that we are using the internal field names.
        //The display name field for the Speaker's name is "Name" and the internal name is "Title". You can see it can 
        //quickly become confusing if your Display Names are completely differnt from your internal names. 
        //For whatever list you want to read from, be sure to specify the fields you want returned. 
        var fieldsToRead =     "<ViewFields>" +
                                "<FieldRef Name='Title' />" +
                                "<FieldRef Name='Blog' />" +
                                "<FieldRef Name='Picture' />" +
                            "</ViewFields>";
                            
        //this is that wonderful CAML query I was talking about earlier. This simple query returns
        //ALL rows by saying "give me all the rows where the ID field is not equal to 0". I then 
        //tell the query to sort the rows by the Title field. FYI: a blank query ALSO returns
        //all rows, but I like to use the below query because it helps me know that I MEANT to 
        //return all the rows and didn't just forget to write a query :)
        var query = "<Query>" +
                        "<Where>" +
                            "<Neq>" +
                                "<FieldRef Name='ID'/><Value Type='Number'>0</Value>" + 
                            "</Neq>" +
                        "</Where>" +
                        "<OrderBy>" + 
                            "<FieldRef Name='Title'/>" +
                        "</OrderBy>" +
                    "</Query>";

        //Here is our SPServices Call where we pass in the variables that we set above
        $().SPServices({
                operation: method,
                async: false,  //if you set this to true, you may get faster performance, but your order may not be accurate.
                listName: list,
                CAMLViewFields: fieldsToRead,
                  CAMLQuery: query,
                      //this basically means "do the following code when the call is complete"
                    completefunc: function (xData, Status) { 
                        //this code iterates through every row of data returned from the web service call
                        $(xData.responseXML).SPFilterNode("z:row").each(function() { 
                            //here is where we are reading the field values and putting them in some JavaScript variables
                            //notice that when we read a field value there is an "ows_" in front of the field name.
                            //this is a SharePoint Web Service quirk that you need to keep in mind. 
                            //so to read a field it is ALWAYS $(this).attr("ows_<internal field name>");
                            
                            //get the title field (Speaker's Name)
                            var name = ($(this).attr("ows_Title"));
                            
                            //get the blog url, SharePoint stores a url in the form of <url><comma><description>
                            //so we only want the <url>. To accomplish this we use the javascript "split" function
                            //whch will turn <url><comma><description> into an array where the first element [0]
                            //is the url.   Catch all that? if you didn't this is another reason you should be
                            //a developer if you are writing JavaScript and jQuery :)
                            var blog = ($(this).attr("ows_Blog")).split(",")[0];
                            
                            //same thing as the blog, a picture is stored as <url><comma><alt text>
                            var pictureUrl = ($(this).attr("ows_Picture")).split(",")[0];
                            
                            //call a function to add the data from the row to a table on the screen
                            AddRowToSlider(name,blog,pictureUrl);
                            
                        });
			//After we have processed all the rows, invoke the slider
                        StartSlider();                
                    }
        });

}

function StartSlider()
{
    //invoke the Content Slider on the div with the id "showcase"
     $("#showcase").awShowcase(
        {
            content_width:  600,  //width for my content (entire slider is wider)
            content_height: 200,  //height for my conebt (entire slider may be taller)
            auto:             true, //auto scroll the slides
            continuous:        true, //keep the scrolling
            arrows:            true, //show arrows so user can click through to sliders
            interval:         4000  //show each slide for 4 seconds
        });        

}

//Add a slide div (class='showcase-slide') to our content slider div (<div id="showcase" class="showcase" />)
//and add content div to our (class='showcase-content') slide div
//Again, very simple example, the content of the slider is a table 
//with the speakers picture on the left, and their name and blog on the right
function AddRowToSlider(name,blog,pictureUrl)
{
    $("#showcase").append("<div class='showcase-slide'>" +      //slide container
                            "<div class='showcase-content'>" +  // content container
                                "<table width='600'><tr>" +     //table with our speaker info
                                    "<td align='left'><img src='" + pictureUrl+ "'></td>" +
                                    "<td align='right'><h1>" + name  + "</h1><br>" +
                                    "<h3><a href='" + blog + "'>" + blog + "</a></h3></td>" +
                                "</tr></table>" +
                            "</div>" +
                        "</div>");
                                
}

</script>

<!-- main div container for content slider -->
<div id="showcase" class="showcase" />

As you can see, we didn't have to change much.

If you want to see the script in action you can view it here: http://www.sharepointhillbilly.com/demos/SitePages/SpeakerSlider.aspx This is also the same slider that I'm using on the main page of my blog.

There are a lot more options with the slider that I haven't even looked at and I have just barely scratched the surface with what it can do. It's times like these that I wish I was more of a designer so I could make it look really sharp. I'll leave that up to you guys though, I'll give you the tools to implement it, if you can help me make it look pretty? Deal?

Anyway, there you go… a hopefully-easy-to-implement jQuery Content Slider for SharePoint. If you want to understand what all the other options are for the slider, be sure to checkout the Awkward Group's website: http://www.awkwardgroup.com/sandbox/awkward-showcase-a-jquery-plugin/ 

Interestingly enough, the above url does not work for IE, it's throwing a JavaScript error :) But it seems to open fine in Chrome.

Thanks again for stopping by. I'm starting to run out of ideas for my Dummiers Guide series, so please feel free to suggest some others.

Comments

Find nodes

Mark, I think people now avoid find("[nodeName='z:row']"), it is not working with recent versions of jQuery.
 on 1/31/2012 12:06 PM

Thanks Christophe

I actually addressed this in the previous blog post. For this script I used jQuery 1.6.4 and SPServices 0.7.0.

I went ahead and updated the script in both blog posts to use:

$(xData.responseXML).SPFilterNode("z:row").each(function(){
});

thanks again for the input...
EMS\markrackleyNo presence information on 1/31/2012 12:34 PM

Great instructonal

Thanks mark for posting two great dummies posts on using jquery especially liked the heavily annotated script.  And the Awkward slider very nice and clean.
 on 1/31/2012 5:31 PM

Backwards Compatible!

Nice post Mark!

I tend to use the cycle plugin for creating sliders, but that's just due being familiar with it.

If you're working in a SP2010 environment you have the ability to use the JavaScript object model, which I personally would recommend, SPServices is great, but the JSOM is there and I'm betting that it'll be a useful skill for vNext too.

Hmmm I might just have to write a complimentary post on that...
 on 2/1/2012 1:45 PM

SPServices vs. Client Object Model

Thanks for the feedback Gavin,

I explained the reasons behind choosing SPServices over the Client Object Model in the previous blog post in this series. Those including:

1) SPServices works in SharePoint 2007 which allows those people to get some value out of the blog post as well.
2) Unless something has changed that I'm not aware of, the Client Object Model does not work with anonymous access. So, it would not be possible to use it on your internet facing site.

That being said, there's definitely value in knowing how to do it both ways, so I look forward to your post.  :)

thanks again,
Mark
EMS\markrackleyNo presence information on 2/1/2012 3:03 PM

SharePoint Architect, Developer, Blogger, Speaker, Author, and general pain in the butt.
 
Thoughts, views, and opinions expressed in this blog are solely my own.
 
Remember, the Impossible just takes longer.
​​​​
 

 Blogs you should be reading