SharePoint - Creating a Rotating Image Banner using JavaScript
Build a rotating image banner in SharePoint 2013 by reading a picture library with REST and swapping an img tag every 5 seconds.
This post shows how to create a rotating image banner in SharePoint 2013. I saw the requirement on SharePoint StackExchange. The images are stored in a picture library.
Scenario
- Upload the banner images to a picture library, for example "ImageLibrary".
- Add an
imgtag to the page. This is the tag that shows each image in turn. - Add the script below to read the library and change the image every 5 seconds.
- Call the script when the page is ready.
The image tag
html
<img id="imageRotator" />
The script
Change siteurl and ImageLibrary to match your site.
js
var arrayOfImageObjects = new Array();
var currentImageIndex = 0;
function GetImagesAndRotate() {
var url = "http://siteurl/_api/web/lists/getbytitle('ImageLibrary')/items?$expand=File";
jQuery.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
},
success: function (data) {
var result = data.d.results;
for (var i = 0; i < result.length; i++) {
var image = result[i];
var imageObject = {};
imageObject.Name = image.File.Name;
imageObject.Url = image.File.ServerRelativeUrl;
imageObject.Width = image.File.ImageWidth;
imageObject.Height = image.File.ImageHeight;
arrayOfImageObjects.push(imageObject);
}
setTimeout(NextImage, 5000);
},
error: function () {
alert("request failed");
}
});
}
function NextImage() {
if (currentImageIndex < arrayOfImageObjects.length) {
jQuery('#imageRotator').attr('src', arrayOfImageObjects[currentImageIndex].Url);
currentImageIndex++;
}
else {
currentImageIndex = 0;
}
setTimeout(NextImage, 5000);
}
$expand=File returns the file details for each item, including its server relative URL. The script stores them in an array and NextImage shows them one at a time, starting again from the first after the last.
Starting it
js
jQuery(document).ready(function () {
GetImagesAndRotate();
});