Carousel of JS / jQuery, PHP with JSON File that gracefully degrades

Tags:

I decided to create a carousel which will be efficient and offer graceful degradation. The only Carousel I came across which offers such feature is the one of Yahoo! Canada (Featured Area of Home Page). Turn off the JS, and you will still see the same layout, with each Items on the right now acting as a link. Upon clicking them will take you to their corresponding page.

In this jQuery Carousel I use PHP to create the layout and using an external JSON File. This will offer degradation for old browsers or when JS is blocked. The Carousel displays either image file or can load a Full HTML File.

The Carousel

Files that will be used:
- class.carousel.php
- jquery.simplecarousel.js
- list.json
- simplecarousel.css

Brief Explanation of the files:

class.carousel.php This is the Class File. All you have to do is initialize the Class and call the Method createCarousel to create the Layout
jquery.simplecarousel.js This is the JS File. The JS was created as a jQuery plugin, and its used just like any other jQuery plugin.
list.json This is the external file which lists the images/html files to be loaded. The filename is customizable
simplecarousel.css This is CSS File used for styling the Carousel.
Details of the Sample JSON File (list.json)
  1. { "entry" : [ {
  2. "type" : "html" ,
  3. "url" : "http://www.yahoo.ca/",
  4. "src" : "/myblog/final/item1.html" ,
  5. "title" : "Batman",
  6. "body" : "Dark Knight Story"
  7. }, {
  8. "type" : "image" ,
  9. "url" : "http://www.flickr.com/",
  10. "src" : "/myblog/final/images/flickr.jpg",
  11. "title" : "Flickr",
  12. "body" : "Its Awesome!"
  13. } ]
  14. }

As you can see, each entry contains 'type', 'url', 'src', 'title', 'body'. Below are the explanation of these terms:
type It can be either 'html' or 'image'
url This is the Link. When type is specified as 'image', then the entire image acts as a link, and the value of link is this url.
src This is the source from where the image or HTML is to be loaded
title This is the title to be shown on 'right' side (depending on Layout)
body This is the body text shown on 'right' side (depending on Layout)

Details of the JS File:
Show Code »
  1. /**
  2.  * A Plugin for jQuery which creates a Simple Carousel. To be used in combination with PHP File & an External JSON File.
  3.  * @author Abdullah Rubiyath
  4.  * @copyright GPL.
  5.  * version 2
  6.  * Usage: $('.featuredDiv').simpleCarousel('pathtoJSONfile');
  7.  *
  8.  * As of now, the only animation available is fade effect, in future I will add more effects
  9.  * @param
  10.  * fileName :
  11.  * params
  12.  * timer : The timer in milliseconds after which the carousel function is called back
  13.  * index : the item index
  14.  * delay : the animation delay
  15.  *
  16.  */
  17.  
  18. (function($) {
  19. $.fn.simpleCarousel = function(fileName, params) {
  20. var $this = $(this);
  21. var cTimer;
  22. if( !params ) { params = { timer: 5000, index: 1, delay: 1000 }; }
  23. return this.each(function() {
  24. $this.next().children('a').click(function() {
  25. window.clearTimeout(cTimer);
  26. $(this).parent().children('class$=on').removeClass('on');
  27. carousel( fileName, {
  28. index : $(this).parent().children().index(this) ,
  29. timer : params.timer
  30. });
  31. return false;
  32. });
  33. cTimer = window.setTimeout( function() { carousel(fileName, params); }, params.timer );
  34. });
  35.  
  36. function carousel(fileName, params ) {
  37. $.getJSON(fileName, function(data) {
  38. $this.animate( { 'opacity' : 0 }, params.delay,
  39. function() {
  40. params.index = (!params.index && params.index!=0) ? 1 : params.index%data.entry.length;
  41. if( data.entry[params.index].type == "image" ) {
  42. $(this).html( $('<a></a>').attr({
  43. 'title' : data.entry[params.index].title ,
  44. 'href' : data.entry[params.index].url
  45. }).append( $('<img />').attr({
  46. 'src' : data.entry[params.index].src,
  47. 'alt' : data.entry[params.index].title
  48. }) ) );
  49. } else {
  50. $(this).load(data.entry[params.index].src);
  51. }
  52. /** taking care of JS -ve Modulu **/
  53. $(this).next().children('a').eq( params.index==0 ? data.entry.length-1 : params.index-1 ).removeClass("on");
  54. $(this).next().children('a').eq(params.index).addClass('on');
  55. ++params.index;
  56. window.clearTimeout(cTimer);
  57. cTimer = window.setTimeout( function() { carousel(fileName, params); }, params.timer );
  58. }).animate({ 'opacity' : 1 }, params.delay);
  59. });
  60.  
  61. }
  62. }
  63. }) (jQuery);

Usage:

Include the CSS and JS File at first. Since this is a jquery plugin, at first include jquery like any other plugin. Then include this js file

  1. <style type="text/css" media="all">
  2. @import url('simplecarousel.css');
  3. </style>
  1. <script language="JavaScript" type="text/javascript" src="jquery.simplecarousel.js"></script>

Now, include the PHP File, intialize the class by passing the JSON Filename as parameter and call the Method createCarousel where you want to show the carousel. You can also set the JSON File later by using the Method setJSONFile()

  1. include 'path/to/file/class.carousel.php';
  2. $carousel = new Carousel('filename.json');
  3. // you can also over-ride it by calling this Method
  4. $carousel->setJSONFile('filename.json');
  5. // now call this Method below to output the Carousel
  6. $carousel->createCarousel();



If you have seen the JS Code, it contains one Method called simpleCarousel(filename, params). Some brief information is below:
  1. simpleCarousel(filename, params);

Parameters:

filenamethe JSON File
params Javascript Object. Attributes are timer, delay and index. timer specifies the time after which the function will be called, by default 'timer' is 5000 (5s). delay is the animation/fade out delay, by default it's 1000 (1s). index is the entry's index in JSON File.
To start the Carousel the following JS Method below

  1. $('.cFeature').simpleCarousel('path/to/filename.json');
  2. // the 2nd parameter is optional and you can use it to over-ride default values
  3. $('.cFeature').simpleCarousel('path/to/filename.json', {timer: 6500, delay : 2000});

The PHP File simply echos the layout and generates the list of related Items on the right column based on JSON File.

The following are the list of classes echoed by PHP by default, but they can be overriden:
cWrapThis is a Wrapper Div of the entire Carousel
cFeature This is the feature Div where the current Item is displayed
cRelated This contains the related Carousel Items.

Now, using the carousel class both cFeature and cRelated can be overriden. If you look inside the PHP Class file, there a public instance variable called '$cssClass', which is an associative array containing two elements 'feature' and 'related'. Just do the following:

  1. $carousel->cssClass['feature'] = 'YOUR_OWN_FEATURED_CSS_CLASS_NAME';
  2. $carousel->cssClass['require'] = 'YOUR_OWN_RELATED_CSS_CLASS_NAME';
Another Important thing is that when you are giving the name of JSON FIle or any other external file name, the PHP Class file adds the prefix '$_SERVER['DOCUMENT_ROOT']' to JSON File all the 'html' source and your provide on JSON File. You can over-ride it by setting the public instance variable prefixPath inside carousel class.

Here's a demo:

Feel Free to block JS and see how it degrades.

Oh, I forgot to mention the file sizes. Its quite small too.
File Sizes:
1. jquery.simplecarousel.js - 2.4kb (normal).. Minified = 1.7kb
2. class.simplecarousel.php - 2kb (normal)

I have attached a zip file containing all the test images, html files along with required ones. Please run 'test.php' file which will output the carousel.
(Note: jQuery File has not been included, so please change the path of jquery file on test.php file to your corresponding jquery.js location)

Files for download:
final.zip

That's it for now!