jQuery: object-oriented slideshow

In this post we're going to create a jQuery slideshow using an object-oriented approach. Why? Consider the situation of the 'previous' and 'next' slideshow buttons. Each button has a click event associated with it that makes the slides move forwards or backwards. The functions associated with each event don't communicate with each other so that one function doesn't know what is the current image to be animated. This is where the Observer Pattern comes into play. By using this design pattern we make sure that both functions are aware of each other. Let's see how.

$('img', '#slider').not(':first').hide();
  
  
  var index = 0;
  
  
  
  var SliderObserver = function(){
  
    
  
    this.current = 0;
    
    
    this.getCurrent = function() {
    
      return this.current;
    
    
    };
    
    this.observe = function(value) {
    
      
      
      this.current = value;
      
      
    
    
    };
  
  
  
  };
  
  
  var observer = new SliderObserver();
  


The SliderObserver object has two methods and one property. The first method retrieves the index value of the current value, while the second set it to the value passed to it. Instead, the current property actually stores such index value. Note that we've also set a variable called index to be incremented or decremented when associated to the slideshow buttons. Let's see how this pattern makes the two functions communicate with each other:

 $('#next').click(function(event) {
  
    index++;
    
    observer.observe(index);
    
    var current = observer.getCurrent();
    
    
    $('img', '#slider').eq(current).show(1000)
    .siblings('img').hide(1000);
    
   
    
    
        
    event.preventDefault();
    
    
  
  
  });
  
    
  $('#prev').click(function(event) {
  
   index--;
   
   observer.observe(index);
   
   var current = observer.getCurrent();
   
   $('img', '#slider').eq(current).show(1000)
   .siblings('img').hide(1000);

   
    event.preventDefault();
  });

When the observe() method is called, it sets the current property to the value stored in the index variable. So if you click first on the 'next' button, current is 1 so that 'previous' will be 0, because the index variable is decremented in the second handler. As you can see, now each function is aware of the value used in the other one. For example:

Values used in the 'next' and 'previous' functions
Next Previous
1 0
2 1
3 2
4 3

And so on. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.