Home > SharePoint 2013, SharePoint Online > SharePoint – Creating a Rotating Image Banner using JavaScript

SharePoint – Creating a Rotating Image Banner using JavaScript

In this post I will show you how easily we can create a Rotating Image banner in SharePoint 2013. (I saw the requirement from http://sharepoint.stackexchange.com/a/139738/34350)

Images are stored in an Images Library (Picture Library)

First you need to place an img tag into the Page. This is the tag which loads Images from Library and cycles images every 5 seconds.

<img id="imageRotator" >

Once this is added, you can use below JavaScript code


	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: { 
				"X-HTTP-Method":"MERGE",
				"accept": "application/json;odata=verbose",
				"content-type": "application/json;odata=verbose",
				"X-RequestDigest": $("#__REQUESTDIGEST").val(),				
			},
			success: function(data){
				var result = data.d.results;
				for(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);
	}

Finally you can invoke this using

	jQuery(document).ready(function(){
		GetImagesAndRotate();
	});
  1. April 27, 2015 at 10:09 PM

    Hi Amal!
    Why do not use standard sharepoint picture slideshow webpart?

    • April 27, 2015 at 10:10 PM

      I was answering the question in Stack Exchange. The user want to use this feature inside his custom webpart.

  1. No trackbacks yet.

Leave a reply to A.m.a.L Hashim Cancel reply