jQuery: vertical image scroller

A jQuery vertical image scroller is simply a container that scrolls when a user performs an action on each image contained within it. In our case, we'll see what happens when a user hovers an image with the mouse. Scrolling has nothing to do with the scrollTo jQuery plugin but only to the CSS top property of the image container which will change according to the vertical offset of each image. As always, we start with our basic markup structure:

<div id="gallery">
  <div id="gallery-wrapper">
    <!--images here-->
  </div>
</div>

Our CSS styles are exactly the same as in any other normal image slider, nothing more:

#gallery {
 width: 90px;
 height: 360px;
 position: relative;
 overflow: hidden;
}

#gallery-wrapper {
 width: 90px;
 height: 720px;
 position: relative;
}

#gallery img {
 display: block;
 width: 90px;
 height: 60px;
 cursor: pointer;
}

Now we need to get the exact vertical offsets of each image. We'll store them in the images themselves using the data() method:

var getImgPositions = function() {

   var $img = $('img', '#gallery');
   $img.each(function() {
   
     var img = $(this);
  img.data('pos', img.position().top);
   
   
   });


};

The pos variable is now attached to every image and contains its vertical offset. We're going to use this offset to make our image wrapper scroll:

$(function() {

   getImgPositions();
   
   var wrapper = $('#gallery-wrapper');
   
   $('img', '#gallery-wrapper').each(function(index) {
   
     var img = $(this);
  
  
  
  img.mouseover(function() {
       
  
      if(index != 0) {
  
        wrapper.stop(true, true).animate({
        top: - (img.data('pos') / 2 ) 
       }, 'slow');
    
      } else {
   
    
        wrapper.stop(true, true).animate({
       top: 0
     }, 'slow');
     
     
     
    
    
      }
   
  
  
  
  });
   
   
   
   });


});

When a user moves his/her mouse over an image, the image wrapper changes its vertical position using the value stored with the data() method. The first image should not be used, so we've used a zeroed vertical offset on it. Further, we've used the index value of the each() method to select the images we want to use. 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.