Display a random picture on your home page

In my last post I introduced the URL protocol for SharePoint lists. Today, let’s see how to use it to display a random picture on a page.

You’ll find other examples on the Web that are based on the same principle. Here is a very popular slide show from Todd Bleeker:

A major difference with the above example is that my code is cross-browser (IE and Firefox), as is usually the case for the other scripts I publish. In this case in particular the behavior of Internet Explorer 7 is actually closer to Firefox than to IE 6.

Another difference is that I release the code as is, not wrapped in a CEWP (lazy me). In my defense, this approach works not only on SharePoint Web Part pages but also on standard Web pages (provided that the user is properly authenticated of course).

The method

We are going to use AJAX, a specific JavaScript technique that allows to interact with the server. The script retrieves the pictures list from the server by using the URL protocol, then randomly selects one for display.

About authentication

With this method we are dealing with several authentication constraints:

1/ The URL protocol: as we have seen in the previous post, the method currently doesn’t work with anonymous access. This is apparently a Microsoft bug.
If you work in an environment with anonymous access, you can still use AJAX but you’ll have to connect to another XML source, like RSS feeds.

2/ The AJAX call: for security reasons, modern browsers apply restrictions on AJAX calls. The exact behavior will depend on your browser, your settings and your environment, so the best is to run tests for your specific case. Usually the requirement is that the picture library and the Web page containing the script  be on the same server. By the way note that this method allows you to display on a site the content from another site…

3/ Of course, the user needs read access to both the Web page that hosts the script and the picture library.

The script

On a SharePoint page: copy the following script and paste it in a CEWP.
In a standard Web page, simply add the script in the body of your HTML.

To make it work, you’ll need to find the unique identifier (GUID) of your picture library. Here are two methods:
– method 1: click on the “upload” button: the GUID appears in the URL, like this:
Convert it as follows: %7B: {   %2D: –   %7D: }
– method 2: view the page source and search for “ctx.listname”

<IMG ID="PicturePlaceholder" src="blank.gif" />
<script type="text/javascript">
// Random Picture
// Questions and comments: Christophe@PathToSharePoint.com

// Enter the parameters for your list or library: ListID, ServerURL, SiteURL

var ListID = "{3D47F1C3-F69F-4930-8D4F-3D4745257AE7}";
var ServerURL = "http://theServer";
var SiteURL = "http://theServer/sites/theSite";

// Start picture retrieval

var URLprotocolURL = SiteURL + "/_vti_bin/owssvr.dll?Cmd=Display&XMLDATA=TRUE&List=" + ListID ;

// Create different XMLHttpRequest objects according to different browsers

var xmlhttp=null;
try {
xmlhttp = new XMLHttpRequest();
} catch(e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support XMLHTTP.");


// The item will be loaded asynchroneously


function StateChange()
if (xmlhttp.readyState==4)
if (xmlhttp.status==200)
alert("Problem retrieving XML data");

function DisplayPicture()
var xmlDoc = xmlhttp.responseXML;
var ListItems = xmlDoc.getElementsByTagName("z:row") || xmlDoc.getElementsByTagNameNS("*","row") ;
var SelectedItem = Math.floor(Math.random()* ListItems.length);
PictureURL = ServerURL + "/" + ListItems[SelectedItem].getAttribute("ows_RequiredField");
document.getElementById("PicturePlaceholder").src= PictureURL ;


A side note about picture libraries

What is the benefit of using a picture library, rather than a standard document library? Well, when you upload a picture to a picture library, SharePoint actually stores 3 versions of your picture:
– the picture you uploaded
– a lightweight Web version, in a folder called “_w”
– a thumbnail, in a folder called “_t”

For example if I upload PictureLibrary/CutePic.jpg, then:
– the Web copy will be PictureLibrary/_w/CutePic_jpg.jpg
– SharePoint will store the thumbnail as PictureLibrary/_t/CutePic_jpg.jpg

Loading pictures usually has a significant performance impact. So, instead of loading the original picture, a better choice could be to pick the Web version or the thumbnail.

Extending the script

You can easily create many variations around the above script.

For example, instead of a picture you can choose to display a quote, a recipe, even – why not – a SharePoint tip!

You can choose a different refresh rate. If you need a picture of the day or quote of the day, you’ll choose a pseudo-random formula based on today’s date. If on the contrary you want the picture to refresh every n seconds you’ll add a loop to your code (see for example Todd Bleeker’s sample).

A usual I’ll be happy to respond to your questions and comments!

38 thoughts on “Display a random picture on your home page

  1. Can you elaborate on how you would go about modifying the script for different ‘randomness’ (i.e. every page refresh, once a day, etc)


  2. My sample script uses the Javascript random function and will call a new item for each page refresh.
    If you want an automatic refresh every n seconds, check out Todd Bleeker’s example (cf. link in my post).
    Javascript doesn’t offer a seeded number generator that would allow you to get the same number all day long, so you have to create one yourself.
    If you don’t care too much about the randomness, you can try simple formulas like this, using the sine function:
    Users adding or removing items from the list once in a while will help make it more random…

  3. Very Nice! One question, if i want to print out an imagedescription below the image, how do in code that in the JS?

  4. How would you dispaly the picture title and description. I checked the return XML, there are no title description fields. Thanks.

  5. Charlie: you first need to edit the default view to include the description. Then you’ll see it in the return XML.
    If you don’t want to modify the default view, then create another view. In this case, it is a little bit more complicated as in the URL protocol you have to precise both the list ID and the view ID.

  6. Christophe, I added to default view title, description and keywords, which are standard picture library columns, none of them show up in the xml. Here is the returned xml:

  7. <z:row xmlns:z=”#RowsetSchema” ows_SelectedFlag=”0″ ows_DocIcon=”jpg” ows_NameOrTitle=”IMG_0508.jpg” ows_ImageSize=”87″ ows_FileSizeDisplay=”8067″ ows_RequiredField=”Purolator Images/IMG_0508.jpg” ows_Preview=”87″/%<

  8. Christophe, it is working, amazing! I reset IIS, it updated the SharePoint, then it works.
    Thank you very much for this great example!

  9. Christophe, this is awesome!

    How would I go about doing a random photo from the _t or _w folders? When I view them, the GUID seems to be the same.

  10. Christophe, first I want to say that I’m certain your efforts have been a god send to a great many people. Saying thank you, just seems wholely inadequate, but “Thank You” very much.

    Second, I have implemented your wonderful solution, but the images are not rotating. I’m not an expert in any of this so I don’t know where to look to help you troubleshooting my problem. Is there anything that you know of right off the top of your head that I might look at changing to rectify this situation? Again, thanks so much for sharing everything with so many.

  11. Well, this is weird but everything just starting working yet I didn’t change a thing! I won’t attempt to figure out why, I’m just glad it is. Thanks again…Rex

  12. Christophe/Charlie: How do I get the description to display along with the random image? I’m not sure what changes I need to make to the coding that you’ve provided above. Any guidance is appreciated!

  13. Pingback: Image rotator: build your own! « Path to SharePoint

  14. I found away around the issue of not being able to use the _t or _w versions of photos. If the pictures in the library are too big for display (digital photos), you can add in the source of this JavaScript resizer to the script:


    I just changed “imageExample” to “PicturePlaceholder,” “imgURL” to “PictureURL” and removed the img URL var line altogether.

    Works perfectly! Now I have a randomly-displaying image, and no matter how big the original photo is, it won’t be any bigger than 300 pixels high or wide.

  15. Hi, i am new to sharepoint…. i want to add a running test on the share point portal which has a public view…. people who login to this share point should read a message that keeps scrolling on the screen (from right to left) (marquee)

    If i have anything that has to be communicated, currently i am adding an announcement but not all lines are visible, hence thought of finding on google.

    May you please help me in getting this done. Either step by step info or video tutior will be of a great help. You can mail me on that too.

    Thanks in advance.

  16. Hi, the script works perfectly well when I run it on a machine that is connected to the local enterprise network. However, if I try to see the slideshow from Internet I get the error: “Problem retrieving XML data”. I checked the value for xmlhttp.status and it is 200 from the LAN and 0 from Internet. Is there a way to submit the correct XML data over Internet or does it work only when the data and the script are on the same server.
    The access from Internet is anonymous. Is this may be the reason for the error? If yes, then how to explain that the access from the LAN does not trigger the error?

    Your help is greately appreciated.

    • Nicola, this solution will only work in authenticated environments, I assume you are automatically authenticated on your enterprise network.
      On the internet, you’ll need to use another data source, for example a RSS feed.

    • var ListItems = xmlDoc.getElementsByTagName(‘z:row’) ;
      if (!ListItems || ListItems.length==0) ListItems = xmlDoc.getElementsByTagName(‘row’) ; //make Chrome work
      if (!ListItems || ListItems.length==0) ListItems = xmlDoc.getElementsByTagNameNS(‘*’,’row’) ;

      • dax, I did some tests, and the latest version of my image rotator (released in March 2010) seems to work well in all browsers including Chrome. Here is what I used:
        var Items=(xml.getElementsByTagNameNS)?xml.getElementsByTagNameNS(“*”,”row”):xml.getElementsByTagName(“z\:row”);
        To be honest, I don’t think I tested Chrome when I released it. It is quite possible that Chrome support for getElementsByTagNameNS was added later.

  17. Great piece (along with the RPC writeup). Can you give me a tip on how I might go about modifying your script to select n images and display them without repeating any picture? I have an image library of 250+ photos, and want to display a random subset of 5 every time the page is loaded, but don’t want the same picture appearing twice in the subset.

    • The solution presented here might not be the best for your case, as it retrieves the whole list of pictures. In your case, you’d be better off just pulling one picture at a time (which would be a completely different script).

      A workaround would be to create a view that only selects 5 pictures based on pseudo-random criteria.

  18. Nice post. I used to be checking constantly this blog and I am inspired!
    Extremely helpful information specially the final phase 🙂 I deal with such info a
    lot. I was looking for this particular info for a long time.
    Thanks and good luck.

  19. Can this technique be used to pull images from a specific folder in the given list? Could I add “+ ‘/thefolderiwant'” to the declaration for URLprotocolURL (after “+ ListID”)? Thanks in advance — it’s really a fine, fine piece of work you’ve produced.

  20. Wow that was odd. I just wrote an really long comment but
    after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all
    that over again. Anyhow, just wanted to say great blog!

  21. Hello and thank you for the post

    I tried it in sharepoint 2013 and i got a problem on the line
    var xmlDoc = xmlhttp.responseXML;

    xmlDoc is null

    Could you please help me

  22. Howdy! I know this is kinda off topic but I was wondering which blog
    platform are you using for this website? I’m getting tired of WordPress because I’ve had issues with hackers and I’m looking at alternatives for another platform.

    I would be fantastic if you could point me in the direction of a good platform.

  23. Excellent post. I used to be checking continuously this blog and I am
    inspired! Extremely helpful info particularly the final part :
    ) I care for such information much. I used to be looking
    for this particular info for a very lengthy time. Thank
    you and best of luck.

Comments are closed.