e-Zest members share technology ideas to foster digital transformation.

Dynamic Carousel built using JavaScript

Written by Ashutosh Khard | Mar 27, 2013 2:25:47 PM

While working on different kind of websites you feel the need of having an image set which will flip and slide. Carousels do that however most of the plugins available don’t pull the images from all over the web. They need images lying on your server from where you pick them up. Also, these plugins are technology or framework dependent.

We also needed a carousel from one of our framework. But in our project we need to pick images spread across the web without wanting to have them readily available at our server location. We couldn’t find any such plugin so we developed our own solution. By the way, this solution is technology independent and hence you can integrate this easily with any technology stack or framework. It require you to have jQuery’s carousel and minified jQuery.js and carousel.css plugin files.

Our carousel also allows user to jump to any image in the carousel without navigating through ‘previous’ or ‘next’ button. User can simply switch to required image acting on the number associated with every image in the carousel.

The UI of the carousel is minimalistic yet elegant. When plugged in the dashboard of the application it gives rich experience of sifting through carousel images.

Having explained about what our carousel can do let’s jump to the code part of the carousel.

Pre-requisites:

  • JavaScript files
    • jquery-1.8.3.js
    • jquery.featureCarousel.min.js
  • CSS file
    • feature-carousel.css
  • Java files
    • CarouselController.java
    • CarouselImageObject.java
  • JSP files
    • carouselIndex.jsp

Other pre-requisites

  • Images folder which contains all the feature Carousel framework related icons. Download link for feature Carousel‘s JavaScript, CSS and images files: https://github.com/bkosborne/jQuery-Feature-Carousel
  • apache-maven

Configuration code

web.xml

	<!-- Creates the Spring Container shared by all Servlets and Filters -->

		org.springframework.web.context.ContextLoaderListener

	<!-- Processes application requests -->

		appServlet
		org.springframework.web.servlet.DispatcherServlet

			contextConfigLocation
			/WEB-INF/spring/appServlet/servlet-context.xml

		1

		appServlet
		*.do

Dependent JARs in pom.xml

			org.springframework
			spring-core
			${spring.version}

			org.springframework
			spring-web
			${spring.version}

			org.springframework
			spring-webmvc
			${spring.version}

			org.codehaus.jackson
			jackson-mapper-asl
			1.8.5

			javax.servlet
			servlet-api
			2.5
			provided

			javax.servlet.jsp
			jsp-api
			2.1
			provided

			javax.servlet
			jstl
			1.2

Source code

CarouselController.java

  /**
 * @author Ashutosh.Khard
 * @version 1.0
 * @created 28 January 2013
 * CarouselController
 *
 * Copyright @ 2013 by e-Zest
 * All Rights Reserved.
 *
 */
package com.ezest.carousel.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ezest.carousel.vo.CarouselImageObject;

/**
 * This is a spring controller which is responsible to render the carousel images form the server.
 *
 * @author Ashutosh.Khard
 *
 * */

@Controller
@RequestMapping("/images")
public class CarouselController {

	/**
	 * This method returns carouselIndex JSP.
	 *
	 * @return carouselIndex represents name of the JSP.
	 * */

	@RequestMapping(method=RequestMethod.GET)
	public String getCarousel(){
		return "carouselIndex";
	}

	/**
	 * This method returns list which contains file name and URL of the image.
	 * This method retrieves all file names from specified folder and then construct URL for those images
	 * This URL is  of the spring controller which is used to get the actual file.
	 *
	 * @return jsonA.toString() represents a string comprising of all the objects containing different images.
	 * */

	@RequestMapping(value = "/jasonData", method = RequestMethod.GET)
	public @ResponseBody List getJasonData( ) {
		// This example is for images stored on local drive, however it could be Amazon S3 and any other location.
		File file=new File("C:\image");
		List list=new ArrayList();
		File[] images= file.listFiles();
		for (File tempFile : images){
			String imageName=tempFile.getName();
			CarouselImageObject carouselImageObject=new CarouselImageObject();
			carouselImageObject.setName(imageName);
			carouselImageObject.setUrl("/carousel/images/getImage.do?imagePath="+tempFile.getAbsolutePath());
			list.add(carouselImageObject);
		}

	return list;
	}

	/**
	 * This method is used to get actual image. When carousel is running, it will hit the image URL to this method which
	 * in turn returns the actual image.
	 *
	 * @param request is a HttpServletRequest object which contains all request information.
	 * @param response is a HttpServletResponse object which is used for HTTP-specific functionality in sending a response.
	 */

	@RequestMapping(value = "/getImage", method = RequestMethod.GET)
	protected void getImage(@RequestParam(required=true) final  String imagePath, HttpServletResponse response) {
		File file = new File(imagePath);
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		try {
			for (int readNum; (readNum = fis.read(buf)) != -1;) {
				bos.write(buf, 0, readNum);
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		byte[] bytes = bos.toByteArray();
		response.setContentType("image/png");
		response.setContentLength(bytes.length);
		try {
			response.getOutputStream().write(bytes);
			response.getOutputStream().flush();
		} catch (IOException e) {
			// Handle the exceptions as per your application.
			e.printStackTrace();
		}
	}
}

CarouselImageObject.java

package com.ezest.carousel.vo;

public class CarouselImageObject {

	private String url;
	private String name;
	@Override
	public String toString() {
		return "{"name":""+name+"","url":""+url+""}" ;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

carouselIndex.jsp

&lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%&gt;<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<link href="css/feature-carousel.css" rel="stylesheet" /><script type="text/javascript" src="js/jquery-1.8.3.js"></script><script charset="utf-8" type="text/javascript" src="js/jquery.featureCarousel.min.js"></script><script type="text/javascript">// <![CDATA[
$(document).ready(function() {
				getJSONData();
			});
		// This function is used to construct the required carousel strucutre by getting images from server (using spring controller).
    	  function getJSONData() {      
    		  $.getJSON("/carousel/images/jasonData.do", 
    		 		function(responce) {
    			  $.each(responce, function(key,item) { 
	   		 		    	var carousleContaierDivId = $('#carousel');
	   		 		    	var imageCarousel = '
<div class="carousel-feature"><a href="#"><img class="carousel-image" alt="Image Caption" src="'+item.url+'"width="380" height="250"></a>
<div class="carousel-caption">
'+item.name+'</div>
</div>

';
    		 				carousleContaierDivId.append(imageCarousel);  
    		 			  });	
    		 			  $("#carousel").featureCarousel(); 
    		 		})
  		 			  .error(function(jqXHR, exception) {
  	  		 				alert("error");
    		 		});
    	   }
// ]]></script>

Carousel Demo

How to make this code run?

Follow the steps:

  1. Place all the images (to be displayed from carousel) in a folder location anywhere in local system or in Amazon S3 volume.
  2. Now mention the same folder path in CarouselController.java. For example, in following example of CarouselController.java “C:\image” is the folder location where all the images are present:
    	@RequestMapping(value = "/jasonData", method = RequestMethod.GET)
    	public @ResponseBody List getJasonData( ) {
    // This example is for images stored on local drive, however it could be Amazon S3 and any other location.
    		File file=new File("C:\image");
    List list=new ArrayList();
    		File[] images= file.listFiles();
  3. Hit http://localhost:8080/carousel/images.do URL from any of your browser.

The URL requested does the following.

  1. The URL hit will result into loading up of a carouselIndex JSP
  2. When DOM is fully loaded “getJSONData()” function of carouselIndex JSP is called which in turn invokes “getJasonData()” function of CarouselController class for fetching up JSON data.
  3. Now this JSON data is fed to an anonymous function of carouselIndex JSP which renders this JSON data’s each and every object and sets the URL and name into a DIV attributes correspondingly.
  4. Now when these DIVs are loaded, then source attribute of each DIV requests for fetching image by invoking “getImage()” function of CarouselController class.