Build a carousel in SharePoint from SharePoint list items using Jquery & Rest

Carousel is a must have element in any kind of web sites that exists in the current world. Carousel not only provides highlights or important information of your web application at the right place, it also minimizes the effort of bringing many information together.

Let’s see how we can use that feature in put it in our SharePoint site home page.

In this article we will learn how can we write a simple html code using j query and rest that will dynamically create a carousel from a SharePoint List and can be reused for as many lists as you want.

The process

  1. Create a list (Promoted Links are best use)

    1. Add metadata values like Title, Description, Background Image and target link
    2. Store background images to a library and remember the location( we will use this in the list items in carousel list)
  2. Use Rest api to read the list items

Lets start with creating a new List

  • Create a List named Carousel and add the metadata fields  into it.

Carousel items
Create List for holding carousel items
  • Add metadata

4
Add Target Url Hyperlink field make it required
3
Description field to display the little data in carousel
6
Add field-name background image of Hyperlink for the images in carousel
  • So we added following metadata fields

    • Description (Multi text field for a little text about the carousel item)
    • TargetUrl ( Hyperlink field-The actual page of the carousel item)
    • BackgroundImage (Hyperlink field-Image related to the carousel item)
  • Upload all the images related to carousel to a document library that are going to be displayed in the carousel.

Now we have  created a list with all the met-data information required and uploaded the images to library. lets add 1 item for carousel

7
Carousel item with all the metadata information

Add few more items like that in the list. I have added four for this article. Feel free to add more.

Now let’s understand what we are going to display

Carousel Item Properties

  1. Title of each item hyperlinked to the target URL.
  2. Description from each item which serves a little background information for the carousel
  3. BackgroundImage as the image that keeps on moving in the carousel
  4. We use following rest Api to get all these values from the list
    1. $.ajax({
      url: “sitename/_api/web/lists/GetByTitle(‘Carousel’)/items”, 
      type: “GET”,
      headers: {
      “Accept”: “application/json;odata=verbose”
      },
      success: function(data){} });
  5. We use Jquery and Html to build the carousel items reading and parsing the Json received from the Rest call.
  6. Finally we use CSS to give it the look of carousel.

So below here is the full code to achieve this. I have added comments in the code section so that it will help you to understand the use of each function.

As in my previous articles i usually write all these codes in a HTML file and use content editor web part to link to the html file. That way  it is cleaner and way easier to maintain.

[code language=”html”]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Carousel</title>
<style type="text/css">
.slider
{

position: relative;
overflow: hidden;
min-height:465px;

}
.slider li
{
position: absolute;
top: 0;
left: 0;
list-style: none;

}
.buttonsnotactive
{
display: inline;
float: left;
background: url(https://theinventor.sharepoint.com/SiteCollectionImages/btnsnotactive.png);
background-repeat: no-repeat;
width: 20px;
height: 20px;
}
.btnactive
{
background: url(https://theinventor.sharepoint.com/SiteCollectionImages/btnsactive.png);
background-repeat: no-repeat;
display: inline;
width: 20px;
height: 20px;
}
a#one_btn:hover
{
background: url(https://theinventor.sharepoint.com/SiteCollectionImages/btnsactive.png);
background-repeat: no-repeat;
}
a#two_btn:hover
{
background: url(https://theinventor.sharepoint.com/SiteCollectionImages/btnsactive.png);
background-repeat: no-repeat;
}
a#three_btn:hover
{
background: url(https://theinventor.sharepoint.com/SiteCollectionImages/btnsactive.png);
background-repeat: no-repeat;
}
a#four_btn:hover
{
background: url(https://theinventor.sharepoint.com/SiteCollectionImages/btnsactive.png);
background-repeat: no-repeat;
}

.buttons
{
width: 50%;
position: absolute;

right: 355px;
top: 450px;

}

.buttons ul{
padding-left:5px !important;
}

.bottomlink {
position:absolute;
bottom:0;
background-color: #e9e8e1;
text-align: left;
margin: 0px !important;
padding:10px;
color: black;
font-weight: 500;
}

.bottomlink a{
line-height: 1.2;
padding-left:5px;
text-align:center;
font-style: italic;
font-size: 20px;
}

.pause
{
display: inline;
float: left;
min-width: 20px;
min-height: 20px;
background-image:url(‘https://theinventor.sharepoint.com/SiteCollectionImages/pausebutton.png’);
background-repeat:no-repeat;
background-color: transparent;
border: none;
margin-top: -5px;

}

.play{
display:none;
float: left;
min-width: 20px;
min-height: 20px;
background-image:url(‘https://theinventor.sharepoint.com/SiteCollectionImages/playbutton.png’);
background-repeat:no-repeat;
background-color: transparent;
border: none;
margin-top: -5px;

}

li.img-carousel {
border: black 1px solid;
width: 500px;
height: 400px;
background-size: contain;
}
</style>

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>

<script type="text/javascript">
$(document).ready(function () {

//call the rest api function
$.ajax({
url: "https://theinventor.sharepoint.com/_api/web/lists/GetByTitle(‘Carousel’)/items", // ur site url goes here
type: "GET",
headers: {
"Accept": "application/json;odata=verbose"
},
success: function(data) {
// log the json data to see the output in console and anlayze the structure
console.log(data);
var i=1;
var j=i+"_btn";
var total= data.d.results.length;
$.each(data.d.results, function(index, item) {
$(".slider").append("

<li class=img-carousel title="+item.Title+" style=’background-image:url("+item.BackgroundImage.Url+");background-repeat:no-repeat;’>
<a class=’read_more_a’ href="+item.TargetUrl.Url+" target=_blank title=" +item.Title+">"+item.Title+"</a> </br>"+item.Description+"
</li>

");
$(".buttons ul").append("

<li class=’buttonsnotactive’ title=’slide "+i+" of "+total+"’><a href=’#’ id="+j+" ></a></li>

");
i=i+1;

})

},
error: function r(xhr) {
alert("error:" + JSON.stringify(xhr));
}
// i am adding the carousel after the rest call that way you avoid the flickering delay in the images
}).done(function(){
var $slider = $(‘.slider’);
var $slide = ‘li’;
// change the transition time and time between slides as required
var $transition_time = 1000;
var $time_between_slides = 5000;
var $btn = $(‘.buttons’);
var $buttonanchor = ‘li’;
// find the li element which holds the carousel
function slides() {
return $slider.find($slide);
}
// fade the slide make the first one active
slides().fadeOut();
slides().first().addClass(‘active’);
slides().first().fadeIn($transition_time);
function button() {
return $btn.find($buttonanchor);
}
button().first().addClass(‘btnactive’);
// this function moves or loops the slides correspond to the buttons
var slideMe = function () {
var $i = $slider.find($slide + ‘.active’).index();
slides().eq($i).removeClass(‘active’);
button().eq($i).removeClass(‘btnactive’);
button().eq($i).addClass(‘buttonsnotactive’);
slides().eq($i).fadeOut($transition_time);
if (slides().length == $i + 1) $i = -1; // loop to start
slides().eq($i + 1).fadeIn($transition_time);
slides().eq($i + 1).addClass(‘active’);
button().eq($i + 1).addClass(‘btnactive’);
};
// add intervals between to restart the slide if it is paused
var $interval = 0;
clearInterval($interval);
$interval = setInterval(slideMe, $transition_time + $time_between_slides);

// function for the buttons to go to respective number slides

$(‘.buttons li’).click(function (event) {
// Added
clearInterval($interval);
// –; —
var $i = $(this).index();
$(‘.buttons li’).removeClass(‘btnactive’);
$(this).addClass(‘btnactive’);
$(‘.slider li’).fadeOut($transition_time);
$(‘.slider li’).removeClass(‘active’);
$(‘.slider li’).eq($i).fadeIn($transition_time);
$(‘.slider li’).eq($i).addClass(‘active’);
if($.cookie("pause")!="yes")
{
$interval = setInterval(slideMe, $transition_time + $time_between_slides)
}
event.preventDefault();
});

// function for play and pause

$(‘#playButton’).click(function () {
$.cookie("pause","no");
$interval = setInterval(slideMe, $transition_time + $time_between_slides);
$(‘#playButton’).hide();
$(‘#pauseButton’).show();

});
$(‘#pauseButton’).click(function () {
clearInterval($interval);
$.cookie("pause","yes");
$(‘#pauseButton’).hide();
$(‘#playButton’).show();
});

})
//end the carousel functions

// end the document.ready
});

</script>

</head>

<body>
<div id="carousel">
<!– div to add the carousel items dynamically –>
<div class="clear"></div>
<div class="slider"></div>
<div class="buttons">
<ul> <!– ul to hold the buttons dynamically –></ul>
<a href="#" class="play" id="playButton"></a>
<a href="#" class="pause" id="pauseButton"></a></div>
</div>
</body>

</html>

[/code]

 

I usually log the json data to console to analyze, if you are doing the same following are the json values we are using in the code.

  • item.Title –> Title of the list item
  • item.BackgroundImage.Url–> Background image of carousel item
  • item.TargetUrl.Url–> Target Url for the particular carousel item
  • item.Description–> Carousel item description

The process logic

  1. Reads the items from the list by using Rest api
  2. Dynamically adds a carousel item to the html
  3. Dynamically adds a carousel button to the html
  4. Depending upon how many items you have in the lists it automatically creates carousel items.

Carousel in the picture

csl
Carousel Item

So the most amazing  thing is now your list is in control of the carousel. you can add as many items you want and your carousel will be automatically updated. You can update or remove any items with new content, the carousel will be automatically adjusted

You can also use this repeatedly across multiple SharePoint sites just change the URL and List name.

I hope you enjoyed the reading.

Note: Please don’t forget to get the images for buttons active, not active, play and pause and update the URL in css to your images.

Here is my home page with carousel in my SharePoint portal.

Homepage
A SharePoint Home page with Carousel

 

Advertisements

Leave a Reply

Your email address will not be published. Required fields are marked *