SPServices Stories #14: Create a Slide Show in SharePoint 2010 using an Announcements List and SPServices

This entry is part 14 of 21 in the series SPServices Stories

Introduction

It’s been a while since I’ve posted a new SPServices Story. This one was sitting in my draft bucket for way too long, so a big sorry goes out to Trace Armstrong (@TraceBArmstrong).

Trace wrote this post about using SPServices to drive a slideshow using an announcements list as the source. This is the sort of common use case that SPServices often sits behind as part of the underlying plumbing.

If you’re using SharePoint 2013 or Office365 running the 15 wave, you might say that one should use REST instead, and that’s an option of course. The nice thing about using SPServices for stuff like this is that if you are on SharePoint 2007 or 2010 or 2013, the SPServices calls are exactly the same. So in a sense, we’ve got easily upgraded code.

Note: I’ve made a few small changes to Trace’s code. One change was to replace .find(“[nodeName=’z:row’]”) with .SPFilterNode(“z:row”). This is required to make things work with up to date versions of jQuery.

Create a Slide Show in SharePoint 2010 using an Announcements List and SPServices

twitter_trace_thumb1By Trace Armstrong

Recently, I had a client who wanted a different slide show for their SharePoint 2010 intranet home page. The original slide show ran using a custom web part that integrated the Nivo Slider, a jQuery based solution. The solution worked great but the person maintaining the news portion of the slider needed a no-code solution for easier updating.

I searched the Internet for a solution and came across this blog (https://www.nothingbutsharepoint.com/sites/eusp/Pages/Creating-your-own-Content-Slider-for-SharePoint.aspx) by Eric on http://www.nothingbutsharepoint.com. The solution was similar to what I needed but my task also required a place for slideshow images.

The first step was using the Announcements list for the announcements slider. I then created two custom list columns, “Image” and “Body”. The “Image” column is a “Hyperlink or Picture” column type and “Body” is a “multiple lines of text” column type.

Using Eric’s model, I referenced SP Services, jQuery, jShowoff, and set about editing the JavaScript code to pull an image column from the Announcements list.

The revised JavaScript looks like this:

$(document).ready(function () {
  var emptyResults = "<div class='sliderDiv'><p class='announceTitle'>Company Name</p></div>";
  var maxVal = 0;
  var toShow = false;
  var heightTemp = 0;
  $().SPServices({
    operation : "GetListItems",
    async : false,
    listName : "Announcements",
    CAMLViewFields : "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Image' /><FieldRef Name='Body' /><FieldRef Name='Modified' /></ViewFields>",
    CAMLQuery : "<Query><OrderBy><FieldRef Name='Created' /></OrderBy>" + "<Where><Or><Geq><FieldRef Name='Expires' /><Value Type='DateTime'>" + "<Today /></Value></Geq><IsNull><FieldRef Name='Expires' /></IsNull></Or></Where></Query>",

    completefunc : function (xData, Status) {
      var itemCount = $(xData.responseXML).SPFilterNode("rs:data").attr("ItemCount");
      if (itemCount > 0) {
        toShow = true;

        $(xData.responseXML).SPFilterNode("z:row").each(function () {
          var modDate = $(this).attr("ows_Modified");
          modDate = modDate.substr(5, 2) + "/" + modDate.substr(8, 2) + "/" + modDate.substr(0, 4);

          var titleHtml = "<div class='sliderDiv'><p class='announceTitle'>" + $(this).attr("ows_Title") + "</p>";
          var imgBody = "<img class='anImage' src='" + $(this).attr("ows_Image").split(',')[0] + "'></img>";
          var bodyHtml = "<p class='announceBody'>" + $(this).attr("ows_Body") + "</p>";
          var expireHtml = "<p class='announceFooter'>Modified: <span>" + modDate + "</span></p></div>";

          //div announcements is added by jshowoff js.

          $("#announcements").append(titleHtml + imgBody + bodyHtml + expireHtml);

        });

      } else {

        $("#announcements").append(emptyResults);

      }

    } //completefunc

  }); //SPServices

  if (toShow == true) {
    $('.sliderDiv').each(function () {
      heightTemp = $(this).height();
      if (heightTemp > maxVal) {
        maxVal = heightTemp
      };
    });
    $('#announcements').css('min-height', maxVal);
    $('#announcements').jshowoff({
      speed : 12000,
      changeSpeed : 3000,
      controls : true,
      animatePause : false,
      effect : 'fade',
      cssClass : true,
      links : true
    });
  } //if stm
}); //ready

I edited a few syntax issues that were unnecessary to the solution and created/referenced a new variable, “imgBody”. The variable adds the img class “anImage” and retrieves the slide show image from the list column “Image”. One of the problems in the solution was SharePoint adding a comma to the end of the file name. The split property removes the comma and the image displayed as intended on the site.

The solution appears like this on the client’s main page.

Slide-ShowThis solution enabled the company to have a no-code update to their main page news slider using an image library and the Announcements list.

Series Navigation<< SPServices Stories #13: Durandal SP3: Developing SharePoint SPAs Made EasySPServices Stories #15: Custom Client-side Calendar Query for Office 365 SharePoint Site Using SPServices jQuery Library >>

Similar Posts

32 Comments

  1. This really helped out a lot! I used this code and tweaked it to work with SP 2013 and Nivo Slider:

    $(document).ready(function () {
      var emptyResults = "Suffolk County!";
      var maxVal = 0;
      var toShow = false;
      var heightTemp = 0;
      $().SPServices({
        operation : "GetListItems",
        async : false,
        listName : "TheList",
        CAMLViewFields : "",
        CAMLQuery : "" + "" + "",
        completefunc : function (xData, Status) {
          var itemCount = $(xData.responseXML).SPFilterNode("rs:data").attr("ItemCount");
          if (itemCount &gt; 0) {
            toShow = true;
            $(xData.responseXML).SPFilterNode("z:row").each(function () {
              var modDate = $(this).attr("ows_Modified");
              modDate = modDate.substr(5, 2) + "/" + modDate.substr(8, 2) + "/" + modDate.substr(0, 4);          
              var imgBody = "";
              var captionHtml = "" + $(this).attr("ows_Body") + "";
                     $("#slider").append(imgBody);
    				 $("#htmlcaption").append(captionHtml);
            });
          } else {
            $("#slider").append(emptyResults);
          }
        } //completefunc
      }); //SPServices
      if (toShow == true) {
        $('#slider').nivoSlider({
    		effect: 'fade',
    		animSpeed: 1000,
    		directionNav: true,
    		controlNav: false
    	});
      } //if stm
    }); //ready
    

    Worked like a charm! I just needed to adjust the CSS a little for branding and controls. I still have some more work to do, but this article got me about 95% there. Thanks again to Trace and Marc!

  2. I essentially got to where Trace did with upgrading the new jquery method for .find. Wish I had found this sooner but learned some things. Was excited I got it working but then realized my users insert huge tables in the body of the announcements. So got a bright idea to add another column called “snippet” and then modify Eric’s code to include the snippet column as follows:

    var bodyHtml = “” + $(this).attr(“ows_Snippet”);+ “”;

    Just to make sure it works I used the same css that was created for the body since essentially it’s just an abbreviated version of body without the tables or pictures. I’m now getting undefined where the Snippet should be. I turned IE9 Developer tools and looked at scripting tab and I get the error:

    Script1002: Syntax Error
    jshowoff.css, line19, character 32

    The above refers to the css set up for the var.

    Not really seeing how css could be getting involved with the undefined error.

    I’ve looked at the underlying XML and copied and pasted the ows_Snippet, thinking I’m tired and I sometimes fatfinger. But the name was okay.

    Any ideas what else I should look at. Thanks in advance for your help.

  3. Marc or Trace,

    I’ve gone through all the steps and while the is pulling the data from the list I cannot get it to look like what you have posted. These are all the files that I’m referencing but obviously I’m missing something. Can you let me know what file (js or ccs) I’m missing.

    Thanks

  4. Marc,

    Unfortunately I’m really bad at writing CSS right now (I’m still learning) and I kind of need a solution now. Would you be able to send me CSS code you used? Or link the code?

    Thanks so much.

    1. @Kyler:

      Looking at the post again, Trace used the jshowoff plugin, which should cover most (if not all) of the styling. When you say “I cannot get it to look like what you have posted”, what’s the issue? Are you getting errors? Things don’t look right?

      You may want to post to a forum that handles code and images better, like StackExchange. Feel free to ping back here with the link.

      M.

  5. Hi,

    This works fine for me for the first run but later on it ends up with all the items in the view. I suppose it should be sliding all the time, please help me with the solution.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.