Creating your own Content-Slider with Pagination using jQuery/CSS

Filed Under: HTML

This Article is in continuation with the tutorial on “Creating Photo-Slider using CSS and jQuery” in “Sliders” series. This will cover following topics in order:-

Contents at a glance…

  1. What is a Content Slider? Advantage of Content Slider.
  2. What is Pagination?
  3. Pre-requisites
  4. Implementing Content Sliders –
    1. Basic Directory Structure.
    2. Layout of the Content Slider.
    3. Explanation of jQuery prototype functions.
    4. Codes for Content Sliders with Pagination and Output.
  5. What’s next?

What’s Content Slider?

As we’ve already seen that Photo Sliders can effectively showcase the images on a limited space of a webpage. But sometime we are needed to display images having some information linked to it. For E.g., textual information, hyperlink to some other page, buttons, other embedded images etc.

In a Content Slider, each of the slides is a DIV container element, instead of a block element like IMG. So you can add as many child element in it. The only restriction is that your contents should be within the limit of slides actual area.

Advantage of Content Sliders over simple image sliders

  1. Contents of any type can be rolled like a slide.
  2. Textual contents can be made dynamic by directly extracting information from other Web sources.
  3. Hyperlink, Button, Audio, and Video etc. can be easily integrated inside a slide.
  4. One of the application is creating an online document reader by properly integrating the slider with Back-end Database.(Seems to be quite tough! I can write a tutorial on that as well.)
  5. All above, Content sliders can be more interactive than trivial Images.

What is Pagination?

Paginations are way of indexing a list with numerals, where each index corresponds to a particular slide. One possible application of Pagination in any slider is the accessibility. At any point, you can directly navigate to a particular slide. They help in sequencing any ordered slider. Users can be guided through your slides using this sequencing mechanism.

Pre-requisites for jQuery Content Slider

This article assumes readers have basic knowledge about what is a webpage, HTML basic tags, few CSS properties and know-how of JavaScript. You can refer to the www.w3schools.com website for these topics. To know more about basic jQuery functions, you can go through other jQuery tutorials posted here. Those who are familiar with these stuffs can directly start with the Implementing Content Sliders section.

Implementing jQuery Content Slider

Now with some basic background of HTML, CSS and JavaScript, we can proceed with the content slider implementation. Just follow the following guidelines;

  1. Creating Directory Structure
    Let’s organize different resources among folders in our Root directory.

    • ‘ContentPagiSlider’ is our Root folder having HTML files with other sub-folders.
    • ‘scripts’ folder contains the Javascript libraries such as jQuery and some other script files.
    • ‘styles’ folder contains CSS files defining styles of different HTML tags.
    • ‘images’ folder contains images used as slides background.

    jquery-content-slider-directory

  2. Creating Layout of Content Slider

    The layout of the slider is as shown in the below figure. Those who have followed the Last tutorial on Creating Simple Photo-Slider using jQuery would see some changes done in the layout of the slider. Actually we’ve added one more parent container element (Class: gallery-container) which encloses the Slider and the Pagination into a single Parent Container.

    For you easiness, I’ve made the layout and pointed the different containers with colors. The dotted line border for “slider-nav” class denotes that only buttons within “slider-nav” are made visible over slides and not the “slider-nav” container.

    jquery-slider-layout

    NOTE: You can Google Chrome’s default code viewer by pressing [F12] and choosing “Elements” tab. Then hover over each element in the code to see how web page elements are highlighted.

  3. Explanation of jQuery “Prototype Functions” in JS file.
    • In jQuery, everything is treated like an Object. Prototype Function is a concept in jQuery, where each function is treated as an object. And each implementing slider object will have its own instance of this method (object). So here in our JavaScript file, ‘transition’ and ‘setCurrentPos’ are the two Prototype functions(i.e. objects) which can have different values for two different slider objects.
    • Using this Concept of Prototype function, we can achieve re-usability of code. That is why we can have multiple sliders within a single page sharing the same code but having its own instance. That’s a very Important Concept!
    • slider() method accepts three parameters and extracts some information like no. of images in the list and width of the image. It also fills the pagination container dynamically by computing the total number of slides in the UL list. For this html() jQuery method is used.
    • The ‘transition’ object in the JS file is for Animation purpose. It calculates the displacement at each move, and which is equal to width of the slide images. It also uses the HTML5 data attribute to identify the current slide with its corresponding pagination element, and then applies the CSS styling.
    • The ‘setCurrentPos’ object calculates the value of ‘current’ counter after the user click on navigation buttons.
    • Based on ‘Next’ or ‘Previous’ button pressed, the value of current is either incremented or decremented. Also if ‘current’ goes below 0, then it’s set to the last element in the list.
  4. The Content Slider Implementation( Codes )

    If you have understood the layout of the slider, let’s understand a trick. One of the problem we face with these content sliders is “Long string sentences” which mostly tend to overflow the slide region. To solve this problem, we’ll be using a CSS property “word-wrap” and set its value as ‘break-word’ which makes it sure that long string words will be broken if they overflow the dedicated width and will be continued on next line.

    The ContentSlider.html file has structural elements along with scripts related to creation of the object for our slider. Observe how each of the slide content is enlisted as the unordered list elements. Two files contentStyle.css and contentSliderScript.js contain styles and methods for controlling the slider motion, direction and also creating dynamic pagination list. You would also need reference to JQuery Library i.e. https://code.jquery.com/jquery-2.1.0.js which you can download and save in the ‘scripts’ folder.

    Codes for all these files are shown below.

    jQuery Content Slider HTML Code
    ContentSlider.html

    
    <!Doctype html>
    <html>
    	<head>
    		<title>Content Slider</title>
    		<link rel="stylesheet" href="styles/contentStyle.css">		
    	</head>
    	<body>
    		<!-- Container for Slider, Navigation and Pagination Controls -->
    		<div class="gallery-container">			
    			<div class="gallery">
    				<h2>Content Slider</h2>
    				<!-- The actual moving Slider -->
    				<div class="slider">
    					<ul>
    						<li>
    							<div class="slides">
    								<div class="slides_content">
    									<img class="bg_img" src="images/bigimg/contentimg1.jpg" alt="Image1" />
    									<h3>
    									<span class="slides_heading">Page 1</span><br/>
    									<div class="text_container"><span class="slides_texts">This is a Plain Text enclosed in a in-line tag onto a Background Image highlighted with a black background.</span>
    									</div>
    									</h3>
    								</div>
    							</div>
    						</li>
    
    						<li>
    							<div class="slides">
    								<div class="slides_content">
    									<img class="bg_img" src="images/bigimg/contentimg2.jpg" alt="Image2" />
    									<h3>
    									<span class="slides_heading">Page 2</span><br/>
    									<div class="text_container"><span class="slides_texts">This is a Plain Text enclosed in a in-line tag onto a Background Image highlighted with a black background.</span>
    									</div>
    									</h3>
    								</div>
    							</div>
    						</li>
    						
    						<li>
    							<div class="slides">
    								<div class="slides_content">
    									<img class="bg_img" src="images/bigimg/contentimg3.jpg" alt="Image3" />
    									<h3>
    									<span class="slides_heading">Page 3</span><br/>
    									<div class="text_container"><span class="slides_texts">This is a Plain Text enclosed in a in-line tag onto a Background Image highlighted with a black background.</span>
    									</div>
    									</h3>
    								</div>
    							</div>
    						</li>
    						
    						<li>
    							<div class="slides">
    								<div class="slides_content">
    									<img class="bg_img" src="images/bigimg/contentimg4.jpg" alt="Image4" />
    									<h3>
    									<span class="slides_heading">Page 4</span><br/>
    									<div class="text_container"><span class="slides_texts">This is a Plain Text enclosed in a in-line tag onto a Background Image highlighted with a black background.</span>
    									</div>
    									</h3>
    								</div>
    							</div>
    						</li>
    						
    						<li>
    							<div class="slides">
    								<div class="slides_content">
    									<img class="bg_img" src="images/bigimg/contentimg5.jpg" alt="Image5" />
    									<h3>
    										<span class="slides_heading">Page 5</span><br/>
    										<div class="text_container"><span class="slides_texts">This is a Plain Text enclosed in a in-line tag onto a Background Image highlighted with a black background.<br/>This is a Plain Text enclosed in a in-line tag onto a Background Image highlighted with a black background.</span>
    										</div>
    									</h3>
    								</div>
    							</div>
    						</li>
    						
    						<li>
    							<div class="slides">
    								<div class="slides_content">
    									<img class="bg_img" src="images/bigimg/contentimg6.jpg" alt="Image6" />
    									<h3>
    									<span class="slides_heading">Page 6</span><br/>
    									<div class="text_container"><span class="slides_texts">This is a Plain Text enclosed in a in-line tag onto a Background Image highlighted with a black background.</span>
    									</div>
    									</h3>
    								</div>
    							</div>
    						</li>
    						
    					</ul>
    				</div>
    				
    				<!-- Navigation Button Controls -->
    				
    				<div class="slider-nav">
    					<button class="backbtn" data-dir="prev">Previous</button>
    					<button class="backbtn" data-dir="next" style="float:right;">Next</button>
    				</div>
    					
    			</div>
    			<!-- Pagination Controls -->
    			<div class="slider-pagi">
    				<div class="pagi-container">
    					<ul></ul>	<!-- Here Paginations will be dynamically created, depending on Number of elements in the list. -->					
    
    				</div>
    			</div>
    		</div>
    		
    		<!-- Loading JavaScript Codes. -->
    		<script src="scripts/jquery-2.1.0.js"></script>
    		<script src="scripts/contentSliderScript.js"></script>
    		<script>
    			// 
    			jQuery(document).ready(function ($) {
    				// creating a container variable to hold the 'UL' element. It uses method chaining.
    				var container=$('div.slider')
    											.css('overflow','hidden')
    											.children('ul');
    				
    				// creating pagination variable which holds the 'UL' element.
    				var pagicontainer=$('div.pagi-container').children('ul');
    				
    				/* 
    				On the event of mouse-hover, 
    					i) Change the visibility of Button Controls.
    					ii) SET/RESET the "intv" variable to switch between AutoSlider and Stop mode.
    				*/
    				$('.gallery').hover(function( e ){
    					$('.slider-nav').toggle();
    					return e.type=='mouseenter'?clearInterval(intv):autoSlider();
    				});
    				
    				// Creating the 'slider' instance which will set initial parameters for the Slider.
    				var sliderobj= new slider(container,pagicontainer,$('.slider-nav'));
    				/*
    				This will trigger the 'setCurrentPos' and 'transition' methods on click of any button
    				 "data-dir" attribute associated with the button will determine the direction of sliding.
    				*/
    				sliderobj.nav.find('button').on('click', function(){
    					sliderobj.setCurrentPos($(this).data('dir'));
    					sliderobj.transition();
    				});
    				
    				/*
    				This will trigger the 'setCurrentPos' and 'transition' methods on click of any Pagination icons.
    				 "data-pgno" attribute associated with the Pagination icons will determine the value of current variable.
    				*/
    				sliderobj.pagicontainer.find('li a').on('click', function(){
    					sliderobj.setCurrentPos($(this).data('pgno'));
    					sliderobj.transition();					
    				});
    				
    				autoSlider(); // Calling autoSlider() method on Page Load.
    				
    				/* 
    				This function will initialize the interval variable which will cause execution of the inner function after every 3 seconds automatically.
    				*/
    				function autoSlider()
    				{
    					return intv = setInterval(function(){
    						sliderobj.setCurrentPos('next');
    						sliderobj.transition();
    					}, 3000);
    				}
    				
    			});
    		</script>
    	</body>
    </html>
    

    CSS Code for Content Slider

    contentStyle.css

    
    *
    {
    	margin:0;
    	padding:0;
    }
    
    /* ============================== This is for Overall Styling of the Content Gallery. */
    .gallery-container
    {
    	border:2px solid olive;
    	margin:10px auto;
    	padding:0px;
    	display:table;
    }
    .gallery
    {
    	width:640px;
    	height:370px;
    	background:#999;
    	/*border:2px solid green;*/
    }
    
    .slider
    {
    	overflow:scroll;
    }
    .slider ul
    {
    	width:100000px;
    	list-style:none;
    	margin-left:0px;
    }
    .slider li
    {
    	float:left;
    }
    
    /* ============================== This is for Navigation Buttons Styling. */
    .slider-nav
    {
    	display:none; /* This is important to hide the buttons if jQuery is Not supported. */
    	margin-top: -10em;
    	cursor: pointer;	
    }
    
    .backbtn
    {
    	position:relative;
    }
    
    .nextbtn
    {
    	position:relative;
    }
    
    /* ============================== This is for Pagination Styling. */
    .slider-pagi
    {
    	/*border:2px solid red;*/
    	text-align:center; /* Important : Keeps the Pagination in the center. */
    	width:640px;
    }
    
    .pagi-container
    {
    	/*border: 2px solid cyan;*/
    	padding: 5px;
    	display: inline-block;  /* This is a good alternative for inline-flex and supports most of the browsers. */
    	/* display: inline-flex; */ /* This is important to remove the extra vertical spaces  between 'UL' and 'pagi-container' */
    }
    
    .pagi-container > ul
    {
    	padding:2px;
    	/*border:1px solid black;*/
    	display: inline-block;
    	text-align: center;
    }
    
    .pagi-container > ul li
    {
    	/* float:left; */ /* Instead write "display:inline-block" Property to set the pagi-elements in center. */
    	list-style:none;
    	padding:0px; /* Setting padding as zero will increase clickable region of child('a' Anchor Element) of LI element */
    	border:1px solid grey;
    	margin: 0px auto;
    	display:inline-block;
    	background: radial-gradient(rgba(255, 255, 255, 0.8) 50%, rgba(180,180,180,0.8));	
    }
    
    .pagi-container > ul li:hover
    {
    	background: radial-gradient(rgba(220, 220, 220, 0.3), rgba(180,180,180,0.8) 95%);
    }
    
    .pagi-container > ul li a
    {
    	display:inline-block;
    	padding:5px; /* This is important to Increase the Clickable Region of the anchor Elements */
    	text-decoration:none;
    	color:rgb(100,100,100);
    }
    
    /* ============================== This is for Styling Each of the Content Slides */
    .slides
    {
    	width:640px; /* This width is reduced to compensate the padding on left and right */
    	height:345px; /* This height is reduced to compensate the padding on top and bottom */
    	word-wrap:break-word; /* Avoids the Text Overflow, and breaks the long Strings/ Sentences on next line. */
    	background-color:rgb(198,185,221);		
    }
    
    .slides_content
    {
    	position:relative; /* Keeps the Slides Content Relative to each Slide */
    	width:100%;
    	height:100%;
    }
    h3
    {
    	position:absolute;
    	width:100%;
    	top:50px;				
    }
    h3 span.slides_texts
    {
       color: white;
       padding:10px;
       letter-spacing: 1px;
       background: rgba(0, 0, 0, 0.5);
       line-height:42px;   
    }
    
    h3 span.slides_heading
    {
    	color: white;
    	display:table;
    	margin:0px auto;
    	background: rgba(0, 0, 0, 0.5);
    	padding:10px;
    }
    
    h3 div.text_container
    {
    	margin:10px;
    }
    
    .bg_img
    {
    	width: 100%;
    	height: 100%;
    }
    

    JavaScript Code for Content Slider

    contentSliderScript.js

    
    /*
    This method will initialize each slider instance.
    Parameter are: -
    ------------------
    1) container -> div.slider ul
    2) pagicontainer -> div.pagi-container ul
    3) nav -> #slider-nav
    */
    function slider(container, pagicontainer, nav){
    	this.container=container;
    	this.pagicontainer=pagicontainer;
    	this.nav=nav.hide(); // This will assign 'nav' from parameters to 'nav' of current slider instance. It uses method chaining.
    	this.imgs=this.container.find('.slides'); // Returns jQuery object containing all matched elements.
        // Following commented line will not work here, as DIVs are Dynamic by nature unlike images where dimensions are known at "PageLoad( )" event.
    	// this.width=this.imgs[0].width;
    	this.width=640; // Only add contents within this limit. Longer sentences will be continued on next Line.
    	console.log('Value of width is : '+this.width);
    	this.imgLen=this.imgs.length; // Returns the total number of sliding elements.
    	console.log("Total no. of Items in the list are : "+this.imgLen);
    	// Here we will fill the Pagination with the following list.
    	out = "";
    	cnt=0;
    	this.liArr = $(container).find('li');// Returns jQuery object containing all matched LI elements.
    	this.liArr.each(function() 
    	{
            out += "<li><a href='#' data-pgno='"+cnt+"'>" + (cnt+1) + "</a></li>"; // Here (CNT+1) is displayed on the WebPage, But the "pgno" attribute starts from ZERO only.
    		cnt++;
        });
    		
    	this.pagicontainer.html(out); // Adding the List to the Pagination Container.
    	this.current=0; // Initialize the "current" counter.
    	// Apply CSS to "First" pagination element in the list.
    	this.pagicontainer.find('li').find("[data-pgno='" + this.current + "']").css({
          border : "2px solid grey",
    	  fontWeight: "900",
    	  fontSize:"18px"
        });	
    }
    
    // This method will apply the needed animation and displacement.
    
    slider.prototype.transition=function(coords){
    	this.container.animate({
    		'margin-left': coords || -(this.current*this.width) // First element is multiplied by Zero.
    	},500);
    	// Remove CSS from Rest other pagination element in the list.
    	this.pagicontainer.find('li a').css({
          border : "none",
    	  fontWeight:"",
    	  fontSize:""
        });
    	// Apply CSS to current pagination element in the list.
    	this.pagicontainer.find('li').find("[data-pgno='" + this.current + "']").css({
          border : "2px solid grey",
    	  fontWeight:"900",
    	  fontSize:"18px"
        });	
    };
    
    // This method will set the "current" counter to next position.
    /*
    Parameters are:-
    ---------------
    1) dir -> It can be either 'prev' or 'next' or else a number denoting slides.
    */
    slider.prototype.setCurrentPos=function(dir){
    	var pos=this.current;
    	console.log('Value of this.value is : '+dir);
    	if(isNaN(dir))
    	{
    		pos+= ~~(dir=='next') || -1; // You can use alternate "Math.floor()" method instead of double tilde (~~) operator.
    		this.current=(pos<0)?this.imgLen-1: pos%(this.imgLen);
    	}
    	else
    		this.current=Number(dir);
    	console.log(this.current);
    	
    };
    

    The source codes have comments wherever it is needed. In case of specific doubt you can ask me directly by commenting below.

jQuery CSS Slider Output

jQuery Content Slider

jQuery Content Slider

NOTE: If you are using Chrome browser and want to debug your scripts, you can Press [F12] key and click on ‘Console’ tab to see how ‘current’ counter is changing on click of a button.

jQuery Content Slider Live Demo

You can see this slider in action by visiting below demo page.

Content Slider with Pagination Demo

What’s next?

Hope you’ve learnt something new and interesting. Get ready for the next article on “Image Sliders with thumbnail view of images” with pagination, vertical sliding and other effects. Happy learning!

NOTE: This article is submitted by Prakash Upadhyay. You can find him on Facebook.

Comments

  1. Pankaj Joshi says:

    How to add infinity images?

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages