Supporters of End User
Web

Creating your own Content Slider for SharePoint

Current average rating is 5 stars. Press SHIFT+ENTER to rate this item.1 star selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+ESCAPE to leave rating submit mode.2 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.3 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.4 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.5 stars selected. Press SHIFT+ENTER to submit. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.
Categories:Javascript and jQuery; CAML; Site Manager/Power User; MOSS; WSS; 2007; 2010

I wanted to add a little bling to a site I was creating and thought I’d create a content slider. Normally this would just be a list of announcements but since space was a concern, a full list wasn’t going to really work. Surely I thought this was a common enhancement that people have done, so I started Binging. I saw many references to image sliders with limited support for making them work for list items. The only other list based content sliders I saw were server licensed products from companies like Bamboo.

So being the hack programmer I am, I thought to myself, “Build your own content slider you dummy.” Surprisingly, it isn’t that difficult, even for hacks like myself.

This article will show you how to create a content slider based on an Announcements list. This can easily be tailored to fit any custom list with a little tweaking. Interested? No? Well it works in both 2007 and 2010, free and server based products. Interested now? I thought so, let’s get started.

Checklist of what’s needed:

So let’s get started. Download jQuery, SPServices and the jShowOff files and store them in your document library on your SharePoint site. If you already have a scripting center in place, you’ll just need to reference the files that exist there and can add jShowOff into those assets. Where ever they’re stored, get the URLs for those files, it’s time to start script building. I’ll break it out into chunks so I can explain what’s happening, then provide a fill script at the end. Jump there if you’ve been to this type of rodeo before and just need to see the solution.

First, we need to reference all the assets:

<script type="text/javascript" src="http://yourSPDomain/sites/site/library/jQuery.js" ></script>
<script type="text/javascript" src=" http://yourSPDomain/sites/site/library/SPServices.js" ></script>
<script type="text/javascript" src=" http://yourSPDomain/sites/site/library/jShowoff.js" ></script>
<link type="text/css" href=" http://yourSPDomain/sites/site/library/jshowoff.css">

This should point to either the uploaded files in the document library or to your scripting center instance. Also note that in my links, I’ve removed all the version attributes from the jQuery and SPServices file names, as that’s just how I roll. Be sure you’re properly referencing your files with however you like to program.

Second, we need to build some styles to make it look presentable. I freely admit I’m not the best designer in the world, feel free to go crazy with the styling. Make it fit your site theme and or corporate brand.

<style type="text/css">
 .sliderDiv	{margin-left:5px; overflow:hidden;margin-top:5px;}
 .announceTitle {font-weight:bold; border-bottom:3px red solid;}
 .announceBody	{padding-left:20px;}
 .announceFooter {font-size:8pt; color:gray;}
 .announceFooter span {font-style:italic;}
</style>

I’m including these after the jshowoff css so I can override any styling that I don’t particularly like.

Now the script. I’ll do my best to chunk this portion up to minimize overload. First is the declaration of the script, to fire when the page has finished loading and set some variables to use later. Change the emptyResults to be anything you’d like to display if there are no results.

<script type="text/javascript">
$(document).ready(function(){ 
var emptyResults = "<div class='sliderDiv'><p class='announceTitle'>There are no current announcements.</p></div>";
var maxVal = 0;
var toShow = false;
var heightTemp  = 0;

Now the heavy lifting of this solution.

$().SPServices({
    operation: "GetListItems",
    async: false,
    listName: "Announcements",
    CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><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).find("[nodeName='rs:data']").attr("ItemCount");
	 if(itemCount > 0){
	  toShow = true;
	  $(xData.responseXML).find("[nodeName='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 bodyHtml = "<p class='announceBody'>" + $(this).attr("ows_Body");+ "</p>";
		var expireHtml ="<p class='announceFooter'>Modified: <span>" + modDate + "</span></p></div>";
		$("#announcements").append(titleHtml + bodyHtml + expireHtml);
       });
	  }
	 else{$("#announcements").append(emptyResults);}
	 }
   });

As you can see, we’re using the GetListItems operation from SPServices to fetch the contents of the Announcments list. We’re telling it to return the Title, Body and Modified date and to retrieve everything with no expiration date or any greater than or equal to Today. Additional fields can be retrieved by simply adding them into the CAMLViewFields section. If you’d like to roll your own CAML, the U2U CAML builder can be used. If you have an existing view created you’d like to use, the Stramit CamlViewer can be used to connect to the list and see the List CAML, as shown in the picture below.

2011-07-09-ContentSlider-01.png

So what is the completefunc doing? Well it’s evaluating the response from the SPServices call. If the ItemCount is greater than zero, we set a variable to true and enter into a loop that builds our announcement divs and appends them to a blank div further down in the code. If no results are returned, the empty message will be added. Fairly straight forward, you can adjust the generated markup if you wish to achieve your desired results, especially if you add more fields into the CAMLViewFIelds.

Last bit of code and we’re there.

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

});
</script>
<div id="announcements"></div>

So if results were returned, then the toShow logic will fire. This finds the height of all the divs that were created and sets the min-height of the output div to the maximum height of all the divs. This eliminates jerkiness of page content as the script rotates through the items. Then the jshowoff function executes the rotation. These are the options I chose, feel free to tinker to get the desired results. A full list of the options is listed below, taken from the jShowOff website.

2011-07-09-ContentSlider-02.png

Here are the two images from my slider. You can see the final slider here

2011-07-09-ContentSlider-03.png

2011-07-09-ContentSlider-04.png

To bring it all together, here’s the full script, happy rotating!

<script type="text/javascript" src="http://yourSPDomain/sites/site/library/jQuery.js" ></script>
<script type="text/javascript" src=" http://yourSPDomain/sites/site/library/SPServices.js" ></script>
<script type="text/javascript" src=" http://yourSPDomain/sites/site/library/jShowoff.js" ></script>
<link type="text/css" href=" http://yourSPDomain/sites/site/library/jshowoff.css">
<style type="text/css">
 .sliderDiv	{margin-left:5px; overflow:hidden;margin-top:5px;}
 .announceTitle {font-weight:bold; border-bottom:3px red solid;}
 .announceBody	{padding-left:20px;}
 .announceFooter {font-size:8pt; color:gray;}
 .announceFooter span {font-style:italic;}
</style>

<script type="text/javascript">
$(document).ready(function(){ 
var emptyResults = "<div class='sliderDiv'><p class='announceTitle'>There are no current announcements.</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='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).find("[nodeName='rs:data']").attr("ItemCount");
	 if(itemCount > 0){
	  toShow = true;
	   $(xData.responseXML).find("[nodeName='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 bodyHtml = "<p class='announceBody'>" + $(this).attr("ows_Body");+ "</p>";
        var expireHtml ="<p class='announceFooter'>Modified: <span>" + modDate + "</span></p></div>";
        $("#announcements").append(titleHtml + bodyHtml + expireHtml);
       });
	  }
	 else      { $("#announcements").append(emptyResults); }
	 }
   });
if (toShow == true) {
	$('.sliderDiv').each(function() {
		heightTemp = $(this).height();
		if (heightTemp > maxVal) {maxVal = heightTemp};  
	});
	$('#announcements').css('min-height',maxVal);
	$('#announcements').jshowoff({ 
		speed:12000, 
		changeSpeed: 1000,
		controls: false,
		animatePause: false,
		effect: 'none',
		cssClass: false,
		links: false
	});
}

});
</script>
<div id="announcements"></div>

Comments

Sherman Woo

Cool!

OMG, I can't wait to try this! As a C# guy with not much front-end skills, this will be an awesome way to scratch quite a few "to-learn" (or at least "to-try" things off my plate). Thanks!

Posted 11-Jul-2011 by Sherman Woo
Daily Creative

Works Perfectly!

Thank you so much!  I am not a SharePoint developer. I am a power user with some expanded responsibilities. I have been searching for this type of solution for so long.  I've only been able to find bits and pieces, but nothing that met my needs so eloquently...specifically for pulling from an Announcements list.  Thank you!!!

Posted 20-Jul-2011 by Daily Creative
Daily Creative

One Little Request

In my opinion, there is only one little thing missing....some indicator or counter of how many announcements that it is scrolling through and which announcement it is on as it is moving.  I love the way it works and looks, but you sort of lose sense of where you are in viewing the announcements until you realized that it has started over.  A user won't know if they are to sit there (and enjoy) 3, 4,5....announcements in the loop.   Any advice on how to add that feature? 

Posted 21-Jul-2011 by Daily Creative
Daily Creative

One Little Request

In my opinion, there is only one little thing missing....some indicator or counter of how many announcements that it is scrolling through and which announcement it is on as it is moving.  I love the way it works and looks, but you sort of lose sense of where you are in viewing the announcements until you realized that it has started over.  A user won't know if they are to sit there (and enjoy) 3, 4,5....announcements in the loop.   Any advice on how to add that feature? 

Posted 21-Jul-2011 by Daily Creative
eric

Thank you!

Thanks for the positive feed back.  I'll look at what I can do to make a X of X display available.

Posted 26-Jul-2011 by eric
eric

Updated

The requested feature has been added.  Check out my site for the download.

Posted 29-Jul-2011 by eric
Abhijit

One more question

Thanks for the Slider... however I would love to know how to adjust the timing of the slider .. Also is there any way to avoid the jump that happens when the mouse hovers over the content

Posted 03-Aug-2011 by Abhijit
eric

adjusting speed

Change the speed and changeSpeed variables to achieve your desired results.  I'll check on the jerkiness you describe.

Posted 03-Aug-2011 by eric
eric

Working on it

If you set the links line to true, you'll get the links and can style them as you'd like.

Posted 18-Aug-2011 by eric
Fidel

Manual rotation

Thanks for a great solution. Will you be implementing a feature where a user will be able to jump to the next announcement instead of waiting for the rotation? this can be handy if there are multiple announcements. Something like a next/previous buttons or even better something like this: Previous 1 2 3 4 5 6 7 Next where the numbers refer to the announcements. thanks

Posted 18-Aug-2011 by Fidel
Fidel

Manual Rotation - Thank you

Great thanks. I'll try that.

Posted 18-Aug-2011 by Fidel
Fidel

Where does the full script go?

Hi, would you please let me know where does the Full script go? on what page? Thank you

Posted 18-Aug-2011 by Fidel
eric

location

As I described in the article, you can place the script in a document library and link to it with a CEWP on your desired page, or you can dump the script into the Source Editor of a CEWP on the desired page.

Posted 19-Aug-2011 by eric
Alex C

Making a reusable web part

Hi. This is exactly what I've needed. Thank you for posting the step-by-step instructions. Any way to turn this into a reusable web part, where we can just pick the list, provide the fields, and have it create a slider for any list? Thanks again.

Posted 28-Aug-2011 by Alex C
Alex C

An issue and solution

I found that when setting links:true returned "undefined" for the links' text. Some debugging found that this was the line in question: var linktext=$(this).attr('title')!=''?$(this).attr('title'):i+1; The title attribute $(this).attr('title') is undefined; so I commented that section so it always gets the i+1 value: var linktext=/*$(this).attr('title')!=''?$(this).attr('title'):*/i+1; Hope this will help anyone else running into this issue.

Posted 29-Aug-2011 by Alex C
Ardid

Almost perfect

All this need to attain perfection is a "read more" button (and consequent trimming of content of course) That way you can make it a News Slider in all its extension.
 
Of course, just a link from each announcement to other list with full news and the idea fulfils anyway.
 
Great work.

Posted 31-Aug-2011 by Ardid
Aaron

Problem

Hi there,
 
amazing solution but im having an issue using this, im a novice so bear with me!
 
i have downloaded the zipped file and put the relevant files into the document library and added the shortcut to the text file.
 
it brings up the no current announcements but isnt scrolling the two items inside my announcements list?
 
hope you can help.
 
im sure its something i have done wrong!

Posted 27-Sep-2011 by Aaron
TexanSteve

Is there a way to get an Image file to show up?

Is there a way to get an Image file to show up?

As I have tried ows_Image and the item only returns a url link.

Posted 27-Oct-2011 by TexanSteve
eric

TexanSteve

Steve, to do that, you'd need to create markup that generates an img tag and uses the ows_Image url as the src.  Something like this:
var imgBody = "<img src=" + $(this).attr("ows_Image");+ "alt='My Image'</img>";

Posted 27-Oct-2011 by eric
TexanSteve

I tried the above code snippet but jshowoff throws an error

but I get an error saying the jshowoff.js needs a Child Element? problem is I can not open the file to get a clean view of it to edit the js file. I get runon code in a big block. Any ideas on how to figure out the child element issue?

Posted 28-Oct-2011 by TexanSteve
mehdi

Content Go Up

Hi
Thanks for this solution
Can you please provide a code for content to go up or down instead of going left ?
and another question :
Can we make the webpart to show more than one item at a time ? for example 3 items at a time and next time another 3 item to show?
Thank you so much

Posted 19-Nov-2011 by mehdi
Sharon

Allow page jump

Hi Eric,
Thank you so much for this.  I have very (very) little programming background so I'm not even going to try it on my own. Is it possible to include page numbers and allow users to click and jump to that page? i.e. display the pages as ◄ 1 2 3 4 5 ►
 
Many thanks,

Posted 29-Nov-2011 by Sharon
Sharon

Allow page jump

just to add to my previous post...I set my links to true but it displayed 'undefinedundefined' on the screen instead of page numbers.  I changed the contolText to ◄► so I just need to show the page numbers in the middle. Thanks again.

Posted 29-Nov-2011 by Sharon
Sharon

Allow page jump

pls ignore my last 2 posts. I figured out a solution by modifying the jshow.js combining the 2 functions for addControls and addSlideLinks and added some <span>&nbsp;</span> to add spaces between the page numbers and ►. Thanks again.
 
But I'm still having problem with the .announceBody, no matter what number I put for padding-left, the text is flushed to the left margin.  It seems like the annouceBody is because when I add border to it, the border is outside the actual body content.
 
 
 
--------------------------------------------
|         announceBody border            |
--------------------------------------------
 
 content is displayed outside the border
 

Posted 30-Nov-2011 by Sharon
Michael Diamond

Allow pause

This is GREAT code that my customers love!  Thank you!
 
Is there a way to make the slider pause after a certain number of animations or to pause it after a certain number of seconds? My customer adds a small number of announcements (2-5) at any one time and would like to see the slider stop after 3-5 cycles. Am I confusing the issue here? I'm sure it's simple, but I just don't see it.

Posted 14-Dec-2011 by Michael Diamond
Ricardo Vigatti

Very good add-on, but i like to change...

Hey, First, I'll like to thank you for this add-on. For me, it works well and provided a great help to a demand. I would like to change just one thing: To change the slides, this plugin seems to use the "mouseover" function somewhere that I can not find. I want to change the script to change the slides happen after the "click" function. How can I do this? Thank you.

Posted 26-Jan-2012 by Ricardo Vigatti
Ricardo Vigatti

I got it...

i could change the way "slider" will slide across its slides. Just add "hoverPause: false" on jshowoff function.

Posted 26-Jan-2012 by Ricardo Vigatti
dtolj

Last published

Is it possible to display the last published content and have it shown first. I have a news List and don't want to display old news but keep it archived.

Posted 14-Feb-2012 by dtolj
Ashish Mishra

Slide picture from Picture Lib

I want to get pictures from Picture Library and show them in slider. But unfortunately its not working for me. I replaced List name with "PictureLibrary" and "ows_Body" with "ows_FileRef". Am I missing anything ?
 

Posted 30-Mar-2012 by Ashish Mishra
tenille

Brilliant Post, additional questions

Hi, Brilliant Post. I am following your post to create a visual webpart for my Sharepoint 2010 Online environment. I am creating a slideshow webpart, where images are selected from a picture library and displayed in a slideshow. I need custom properties in my web part to allow the user to select 1. to reduce the size of the images; 2. background colour; 3. Types of Transition; 4. Length of display; 5. Image Text and Description and where to put this; 6. Size of the web part (to reduce whitespace around image). I do know that I have to use J Query, XSLT and CSS to style and rotate the images, but I don't know how to get my web part properties from the web part to my XSLT and Javascript. I need the values entered by the use to be used to set the values in the javascripot to control how the slideshow is executed. Do you know if there is an alternative to using the plug ins you have mentioned, as my environment doesnt allow add on plug ins, I just have the usual JQuery that comes with SharePoint 2010? Then I have to package all this into a Sandboxed solution for deployment. Can you help? thanks in advance.

Posted 10-May-2012 by tenille
Hemant

For jShowOff to work, the container element must have child elements

I am now getting the following message: "For jShowOff to work, the container element must have child elements." Can you give some suggestions on how to resolve it ?

Posted 11-May-2012 by Hemant
Andy Bonner

Update required for jQuery 1.7 or higher

If anyone wants to get this working with jQuery 1.7 or higher make sure you get the latest version of SPServices as well(v0.7.0 or higher) then you need to replace the following lines
 
 var itemCount = $(xData.responseXML).find("[nodeName='rs:data']").attr("ItemCount");
with
var itemCount = $(xData.responseXML).SPFilterNode('rs:data').attr("ItemCount");
 
and
$(xData.responseXML).find("[nodeName='z:row']").each(function() {
with
$(xData.responseXML).SPFilterNode('z:row').each(function() {
 
 

Posted 12-Jun-2012 by Andy Bonner
bijesh

Place to insert the code

Where will i put the script into...A content editor or in the page

Posted 15-Aug-2012 by bijesh
Katherine Williams

More than 1 List

Am I able to add more than 1 list to the rotation? I have 3 lists I would like to have rotate here and just not sure of the steps required to make that happen.

Posted 14-Sep-2012 by Katherine Williams
James Temens

Show an attachment

How would you show an attachment from a list (for instance a jpg file)?  I can retrieve the field from the query but, I'm not sure how to get the attachment to show up.

Posted 01-Nov-2012 by James Temens
denisse

Link to announcement

Hi, Great add-on for the announcements! One question, how do you link the announcement on each sliders?

Posted 30-Jan-2013 by denisse
kend

Link to announcement

Anyone had any luck with linking the result in the Title column to the announcement? Thanks

Posted 18-Mar-2013 by kend
Graham Thompson

Getting an error

Was looking forward to seeing this working. Did everything that was required, but when I copy the URL into the CEWP and 'test the link', all I get is;
 
Webpage error details
User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)
Timestamp: Mon, 25 Mar 2013 23:34:06 UTC

Message: Object expected
Line: 14
Char: 1
Code: 0
URI: /Slider/slider2.txt
 
HELP!!

Posted 25-Mar-2013 by Graham Thompson
Randy

Slider Animation Jerky

I notice at the beginning and end of each fade transition, the entire announcement jerks up & down. Any known solutions. Abhijit mentions the same issue in the thread above.

Posted 03-Jun-2013 by Randy
Kerry

Allow page jump

The person who asked this question managed to figure out herself how to have the navigation as < 1 2 3 4 > but never poste the solution. I don't know any javascript but have tried to change the order and remove the paragraphs - I got as far as changing <p> to <span> which seemed to work ok and put everything onto the same row but don't know how to change the order without messing up the code. Can you help?
 
 

Posted 23-Jul-2013 by Kerry
david keeley

thank you

works great and really catches the eye instead of a static list - thank you - if anyone has information on using the same to show pictures let me know ! - cheers

Posted 02-Aug-2013 by david keeley
Mima

Found the same with pictures, but have trouble getting it to work...

HI, I found this script with pictures, but cannot get it to work... Please help! Thanks a lot!!! --------------------------------------

Posted 07-Aug-2013 by Mima
Eric

Script location

Does this go into a content editor?

Posted 08-Aug-2013 by Eric
Mima

Re: Script Location

I put it on a Script Editor WP...

Posted 08-Aug-2013 by Mima
Lisa R

Can't see the final product

The description sounds like what I'm looking for but I don't see a demo -- I get a 404 error for your link to the slider example: http://spdwiki.com/SitePages/ContentSlider.aspx

Posted 15-Aug-2013 by Lisa R
Bani

Can't see the Announcements Slider

It always says 'There are no current announcements.' ... What is wrong here ? Can you guide please....

Posted 04-Sep-2013 by Bani
Robert Merritt

Does this still work?

I always get "There are no current announcements.

Posted 25-Sep-2013 by Robert Merritt

Notify me of comments to this article

E-mail:
   

Add Comment

Title:

 
Comment:
Email:

   


Name:

 
Url: