Archive

Posts Tagged ‘picture library’

SharePoint – Creating a Rotating Image Banner using JavaScript

April 27, 2015 2 comments

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();
	});