Pages

7/17/2009

SharePoint: Rotating Pictures, Random Pictures (updated)

 

Yet another update!  People can be such a pest… you keep asking for “captions, for buttons, for Play/Pause… Well I finally took the time to do it. Rather than complicate this post any more, I have the update here:
http://techtrainingnotes.blogspot.com/2010/05/sharepoint-rotating-pictures-random.html

Here’s a what the updated one looks like (without the animation):

image

 

SP 2010 Update: Will this work in SharePoint 2010?  Who cares!  SP 2010 has a new “Picture Library Slide Show web part” that can display random pictures every “x” seconds! (But my new version above is customizable!)

 

Updated to support Firefox and to add an optional hyperlink.

 

Many web sites have pictures that keep changing while the page is displayed. If you were doing ASP.NET development you might use the AdRotator control to do this. You can find some custom web parts that can be installed on your web server to do this.

But… I wanted a way to do this with no C# programming, no server deployment issues and even without SharePoint Designer. This is yet another Content Editor Web Part trick!

 

How this works:

  • Add a picture library and upload some pictures
  • Add a the web part for this new library on your home page
  • Customize the view used by the web part
  • Add a Content Editor Web Part to the same page and paste the HTML and JavaScript code below
  • Sit back and watch!

Options:

When you paste the JavaScript you can set a few options to control the appearance of the images:

  • One is required:
    • The name of the web part
  • The rest are optional:
    • Show in thumbnail size (160 pixels wide) or full size
    • Show in the order found in the web part or random
    • Set how long each picture is displayed
    • Set how long to take to transition between images
    • Set if you would like to make the images clickable to a custom URL

Important note: This has only been tested in Internet Explorer and Firefox 3.5.2 so far. I will try to some testing with other browsers soon.

 

Steps:

  • Create your picture library and upload your pictures
  • If you would like to supply links for the pictures, add a hyperlink column
  • If you would like to filter the list of pictures to be displayed, customize the library to add additional columns to how the filter data. (Event name, department, product, etc)
  • Go to your web part page and add the web part for the new library
  • Important steps:
    • Click Edit, Modify Shared Web Part
    • Optional: In the appearance section give the web part a meaningful name
    • Click Edit the Current View
    • Un-checkmark all of the columns except for “Name (linked to document)”
    • Optional: check a column to use as a custom hyperlink (must be the second column in the view)
    • Optional: Set the sort order
    • Optional: Set filter options to select only the pictures you want displayed
    • Make sure the the list web part view is not using a "Item Limit" less then the number of pictures in the list. (You could just set this to be BIG number).
    • Click OK to save the view changes
    • Click OK to save the web part changes
  • Add a Content Editor Web Part (CEWP) below the picture library web part
  • Click Edit, Modify Shared Web Part
  • Click Source Editor
  • Copy and paste the code from below
  • Click OK for the Source Editor
  • Click OK to save the web part changes
  • Click Exit Edit Mode and see if it works!

The Code:

 

<script>
// another CEWP trick from http://techtrainingnotes.blogspot.com
var pictureWebPartName="Airshow Pictures"; // name of the picture library web part
var showThumbnails = true; //otherwise show full sized images
var randomImg = true; //set to true to show in random order
var useCustomLinks = false; //true to use second column as URL for picture clicks
var RotatingPicturesLoopTime = 5000; //2000 = 2 seconds
var imgToImgTransition = 1.0; //2 = 2 seconds

// don't change these
var selectedImg = 0;
var imgCache = [];
var imgTag;

function RotatingPictures()
{

imgTag = document.getElementById("RotatingImage");
//Find the picture web part and hide it
var Imgs = [];
var x = document.getElementsByTagName("TD"); // find all of the table cells
var LinkList;
var i=0;

for (i=0;i<x.length;i++)
{
if (x[i].title == pictureWebPartName)
{
// tables in tables in tables... ah SharePoint!
LinkList = x[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
// hide the links list web part
// LinkList.style.display="none";
break;
}
}

if (!LinkList)
{
document.all("RotatingImageMsg").innerHTML="Web Part '" + pictureWebPartName + "' not found!";
}

//Copy all of the links from the web part to our array

var links = LinkList.getElementsByTagName("TR") // find all of the rows
var url;
var len;
for (i=0;i<links.length;i++)
{
//if (links(i).id.match("row")!=null)
if (links[i].childNodes[0].className=="ms-vb2")
{
len=Imgs.length
Imgs[len]=[]
Imgs[len][0] = links[i].childNodes[0].childNodes[0].href;
if (useCustomLinks)
{
if (links[i].childNodes[1].childNodes.length>0)
{ Imgs[len][1] = links[i].childNodes[1].childNodes[0].href; }
else
{ Imgs[len][1] = "" }
}
}
}
if (Imgs.length==0)
{
document.all("RotatingImageMsg").innerHTML="No images found in web part '" + pictureWebPartName + "'!";
}
for (i = 0; i < Imgs.length; i++)
{
imgCache[i] = new Image();
imgCache[i].src = Imgs[i][0];
if (useCustomLinks)
{
imgCache[i].customlink=Imgs[i][1];
}
}
RotatingPicturesLoop();
}


// now show the pictures...
function RotatingPicturesLoop()
{
if (randomImg)
{
selectedImg=Math.floor(Math.random()*imgCache.length);
}

if (document.all){
imgTag.style.filter="blendTrans(duration=" + imgToImgTransition + ")";
imgTag.filters.blendTrans.Apply();
}

url=imgCache[selectedImg].src
if (useCustomLinks)
{ RotatingImageLnk.href=imgCache[selectedImg].customlink; }
else
{ RotatingImageLnk.href = url; }

if (showThumbnails)
{
// convert URLs to point to the thumbnails...
// from airshow%20pictures/helicopter.jpg
// to airshow%20pictures/_t/helicopter_jpg.jpg

url = revString(url);
c = url.indexOf(".");
url = url.substring(0,c) + "_" + url.substring(c+1,url.length);
c = url.indexOf("/");
url = url.substring(0,c) + "/t_" + url.substring(c,url.length);
url = revString(url) + ".jpg";
}


imgTag.src = url;
if (document.all){
imgTag.filters.blendTrans.Play();
}
selectedImg += 1;
if (selectedImg > (imgCache.length-1)) selectedImg=0;
setTimeout(RotatingPicturesLoop, RotatingPicturesLoopTime);
}


// utility function revString found here:
// http://www.java2s.com/Code/JavaScript/Language-Basics/PlayingwithStrings.htm
function revString(str) {
var retStr = "";
for (i=str.length - 1 ; i > - 1 ; i--){
retStr += str.substr(i,1);
}
return retStr;
}


// add our function to the SharePoint OnLoad event
_spBodyOnLoadFunctionNames.push("RotatingPictures");

</script>

<!-- add your own formatting here... -->
<center>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td id="VU" height="125" width="160" align="center" valign="middle">
<a name="RotatingImageLnk" id="RotatingImageLnk" alt="click for larger picture">
<img src="/_layouts/images/dot.gif" name="RotatingImage" id="RotatingImage" border=0>
</a>
<span name="RotatingImageMsg" id="RotatingImageMsg"></span>
</td>
</tr>
</table>
</center>



 



 


 



 



.

47 comments:

Shawn said...

Is it possible to include a url for the image to link to as well?

Anonymous said...

I tried this and just got a blank screen. I'm using IE7. Any ideas?

Mike Smith said...

Shawn,

Sure! I just added above.

Mike

Mike Smith said...

> I tried this and just got a blank screen. I'm using IE7. Any ideas?

I tested it on IE7, so that's not it. Do you see a red "X"? Did customize the list web part to show only one column ("Name (linked to document)")? Also make sure the the list web part view is not using a "Item Limit" less then the number of pictures in the list. (You could just set this to be BIG number).

Mike

John Mc said...

cut and paste the code form this blog to the source editor in IE - the code has no carriage returns, and is effectively one long line, which makes all the code commented out. I opened this blog in firefox and copied the code and then pasted it into the content editor in IE - the carriage returns remained. I added my photo library name, and it works fine now! Thanks

Anonymous said...

Thank you this is fantastic!

Just an FYI.
It works great on IE, but it does not work for Firefox 3.5 nor Safari.
No worries because we only use IE in our Intranet, however it would be so awesome if it could also be utilized for Firefox and Safari in the future.

Again sincere thanks!

manny said...

Is it possible to have the image link to the hyperlink created in the picture library or if not just turn off the link to on the image?

Mike Smith said...

manny,

I don't think I'm clear on what you are asking.. but if don't want the link from the image remove these lines:


RotatingImageLnk.href = url;

and at the end:



and

Anonymous said...

Great stuff. Is there a way to add URLS to the images?

Mike Smith said...

> Is there a way to add URLS to the images?

The example code does have a URL to the images. Are asking if there can be links to some destination other than the image?

Unknown said...

I have the following problem trying to apply this trick. I followed the instructions all the way through and now i'm stuck cause the CEWP (where i paste the source code) gives me :"Webpart MyWebpartname not found!". I double-checked the source code, and there is no mistake in writing the name of the webpart.

any solution on this?

Unknown said...

FYI: The problem i had was caused du to the Desvription i have added to my library. The name plus the description of the library together form the Title your script is searching for like :

title="libraryTitle - Description"

Wiktor said...

Hi Mike,
any chance you will make it work for Firefox and Safari?

Mike Smith said...

I have updated the JavaScript to support Firefox and to add a clickable link for each picture.

Mike

Bill Burke said...

When I set the "Pictures" web part to "Hidden" the CEWP says "Web Part 'Pictures' not found!"

Does the pictures WP need to be visible?

Mike Smith said...

Bill,

Don't hide the web part. Uncomment this line:

// LinkList.style.display="none";

I forgot and left it commented out.

Mike

martin said...

My pictures don't display just a broken link icon.

I dug around and found the links that work and don't work as posted below:

Working picture link:(as show from the picture library list)
http://www.grandblancfamilyfunfest.org/2007%20Photo%20Gallery/_t/PICT3456_jpg.jpg

Non working Link:(as show from the script)
http://www.grandblancfamilyfunfest.org/2007%20Photo%20Gallery/Forms/_t/DispForm_aspx?ID=32.jpg

Any ideas?
Thanks!

Mike Smith said...

Martin,

Your first link goes to a picture, then second goes to a web page (DispForm_aspx) that might display a picture. The link needs to be to a picture. To test, type the URL into a browser and make sure that it only displays the picture and nothing else.

Mike

determs said...

The error about the missing web part holds true when you hide the title of the page when publishing, make sure to leave this visible.

determs said...

I really love this concept, the problem is I have hundreds of images I am randomizing, is there any other options to speed the loading? I notice that it is 'downloading' several pictures in the beginning.

Mike Smith said...

toaster,

No need to hide the list web part if this line is not commented out:
// LinkList.style.display="none";

> I notice that it is 'downloading' several pictures in the beginning

In the list web part are you including anything that shows the image? This list should just have rows and columns of list data.

Mike

determs said...

// LinkList.style.display="none";

Yes I have unhid that but there is an option to not display the "title" of the web part, which I typically do. However, if you set the property to 'none,, it cannot find that on the page. It makes sense just wasn't thinking it through.

About the other question, yes I only have the list showing up as a linkable filename. At this time I have over 150 images we are rotating through because I eventually want to expand this into a 5 image randomizer.

-cheers

keyymann said...

I'm surprised no one has asked this: what about adding image captions?

Mike Smith said...

Jacob,

Captions?

I thought someone had... oh well...

It would not be too hard, just add a new column to the picture library with the text, add a new column to view used in the web part and read and display that text similar to how the useCustomLinks code works.

Mike

mikie was here .... said...

this is great !!! excellent work !!!

if someone can get captions to work I would sure like to see that !!!

thanks

:)

Krystal said...

This is great! I added the web part as described, but now the page loads with an error of:

Message: 'imgCache[...].customtext' is null or not an object
Line: 1590
Char: 6
Code: 0

Any ideas?

Thanks

Chris said...

This is great for a newbie like me. I am a bit stumped that the script says my web part can't be found. I am using the name from my pciture libary i.e. "My Pictures"

Any suggestions?

Mike Smith said...

Chris,

Check to see if your picture library also has a description. If so, it must be included in the name in the JavaScript.

Without a description:
var pictureWebPartName="Airshow Pictures";

With a description of "Sample Pictures":
var pictureWebPartName="Airshow Pictures - Sample Pictures";

Notice that the name is case sensitive and if you have a description then the name is:
name - description

Mike

Unknown said...

This is just what I've been looking for!

I'm having a bit of trouble. I can't seem to get anything rotating. I'd like to have randon, rotating images that when clicked, take you to a different page.

I've created a Picture Library, populated it with some images, and added a hyperlink column. On my home page, I've added the list view web part of that same Picture Library and edited the view to only include the Name(linked...)column and my additional hyperlink column. Below that, I added a CEWP, copied and pasted your code, and changed two variables; pictureWebPartName and useCustomLinks.

All I see is a list of the file names of the images. Nothing is rotating. Any thoughts?

Mike Smith said...

bluepagoda,

The Title can be the Title or the Title + Description, depending on your library.

Best way to find what is needed it to display the page with the Picture Library web part, right-click the page and select View Source. Then search for title="My Pictures (or whatever your library name is) (note: starting quote(") only).

You will then find something like title="My Pictures - Pictures from the airshow". So the full title is the library's title plus the library's description: My Pictures - Pictures from the airshow

A second option is to just remove the description from the library, if it is not really needed.

Mike

Anonymous said...

Great post Mike !! Is it possible to add multiple such webparts on the same page? I am having some difficulty accomplishing that.
Shankar.

Allen said...

Hi Mike,

I'm getting a blank web part and the browser is throwing up an error stating the following.

'childNodes.1.childNodes' is null or not an object.

Can you please help.

Cheers
Allen

Mike Smith said...

Allen,

Most likely your "custom links" column is not set up right. Try turning this off and then test:

var useCustomLinks = false;

Mike

Allen said...

Hi Mike,

Thanks for your response. Yes. I did have a problem with custom links. I turned that to false and it all started coming together.

Another challenge that I had was that thumbnails was not getting displayed. I was getting an 'X'. I turned that to false and the original images started getting displayed. So all is well.

Thank you once again for your support.

Regards,
Allen

sukumar said...

var pictureWebPartName="http://bhelmoss:12337/PictureSlideShow";


picture library webpart not found

pls help this error

Mike Smith said...

sukumar,

You need to supply the name of the picture library web part you added to the page, not the URL to the library. To find the web part's name, use the browser's view source command to see the HTML of the page then search for the picture library.

Check to see if your picture library also has a description. If so, it must be included in the name in the JavaScript.

Without a description:
var pictureWebPartName="Airshow Pictures";

With a description of "Sample Pictures":
var pictureWebPartName="Airshow Pictures - Sample Pictures";
(The "-" may not be there in 2010.)

Notice that the name is case sensitive and if you have a description then the name is:
name - description

Mike

Susan said...

I saw Allen wrote: "I was getting an 'X'. I turned that to false and the original images started getting displayed. So all is well."

My Question - WHERE do you turn something to false?

I'm getting the little red X too.

Thanks!

Mike Smith said...

Susan,

Most likely this line:

var showThumbnails = true;

Mike

Unknown said...

I've been trying to customize the size, color of the font. The color seems to be doing just fine, but I've been unable to adjust the size of the font.

Is there any way to change the alignment of the caption in relation to the photo?

Mike Smith said...

Briana,

Go to the updated version of this article:

http://techtrainingnotes.blogspot.com/2009/07/sharepoint-rotating-pictures-random.html

Find this section and add your styles to it:

<span name="RotatingImageText" id="RotatingImageText"></span>

Like this:

<span style="color:red;font-size:30pt" name="RotatingImageText" id="RotatingImageText"></span>

The caption is located in its own row, but you can restructure the HTML of the table and put it anywhere.

Mike

Unknown said...

Mike,

Spoke too soon. Fixed the font issue but I'm not sure what you mean when you say to restructure the HTML of the table to move the caption. My knowledge of code is pretty limited.

Thanks again for your help.

Mike Smith said...

Briana,

The HTML section is the part after:
<!-- add your own formatting here... -->

Do you work with anyone with basic HTML skills? They'd have no problem redesigning this for you.

Mike

Unknown said...

How would I go about specifying outputted image size? Thumbnails are too small and full size is too large.

Mike Smith said...

Paul,

The best approach is to edit the pictures to the correct size before uploading. Otherwise, you can add HEIGHT and WIDTH attributes to the IMG tag:

<img src="/_layouts/images/dot.gif" name="RotatingImage" id="RotatingImage" border=0 WIDTH=100 HEIGHT=100>

Mike

Unknown said...

That fix works great! Having issues with making the image clickable to a custom URL. Advice? Both images and custom text field work perfectly.

Also, I tried to add another custom text field (ex. original custom text field - title (font bold), secondary custom text field - description (font regular). I have a quick fix in place by using html tags, however if anyone else uploads pictures the formatting will be all off. I copied and pasted all coding referring to the customText, calling the additional field customDesc and linked to column 3 but with no luck. When I saved the changes, the images disappear.

Anonymous said...

Everything is working great except that it is not picking up all my photos. I have 14 in the library but it's only rotating through 4 of them. And only 4 of the new photos I just uploaded. There is nothing I can see that limits the number to display. Any ideas? Using SharePoint 2007 with IE 7.

Mike Smith said...

Anonymous,

Check the View setup for the list web part to see if it is setup for paging.

Mike

Post a Comment

Note to spammers...
Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.