jQuery Image Scroller Plugin

Trevor Davis, Former Front-End Development Technical Director

Article Category: #Code

Posted on

Building websites for PUMA has given me the opportunity to do some pretty cool stuff. The latest feature was dreamed up by Owen, and it turned out to be pretty easy to do with JavaScript.

These large individual product images work great for products like shoes, but when we needed to introduce clothing items we couldn't fit the entire product in without shrinking the image down until it was too small. Owen’s solution was to have a small thumbnail preview that you could drag over to view different sections of a larger image.

So with a little bit of jQuery, I was able to make that happen, and I made a plugin out of it.

If you just want to skip ahead, check out a simple demo and download the plugin.

Markup

So the idea is that we have a container (.image-scroller) with a fixed height and width, an image that is taller than the container (.feature-image), and a container (.preview) for the thumbnail of that image:

<div class="image-scroller">
  <img src="images/feature.jpg" alt="" class="feature-image" height="1280" width="960" />
  <div class="preview">
    <img src="images/preview.jpg" alt="" height="180" width="135" />
  </div>
</div>

Just a Dash of CSS

We really just need to assign some heights, widths, and positioning:

.image-scroller {
  height: 640px;
  -moz-user-select: none;
  overflow: hidden;
  position: relative;
  -webkit-user-select: none;
  width: 960px;
}
.image-scroller img {
  display: block;
  left: 0;
  position: absolute;
  top: 0;
}
.image-scroller .preview {
  border: 5px solid #fff;
  bottom: 20px;
  height: 180px;
  left: 20px;
  position: absolute;
  width: 135px;
}

Once the plugin is applied, there is a span with a class of indicator appended to the small preview area which represents the area you can drag up and down:

.image-scroller .preview .indicator {
  background: #000;
  cursor: move;
  display: block;
  left: 0;
  position: absolute;
  width: 135px;
}

Make it Move with JavaScript

You’ll need to start by including jQuery and my plugin on the page:

<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/jquery.imageScroller.min.js"></script>

Then, you can just call the plugin on the container:

$(document).ready(function() {
  $('div.image-scroller').imageScroller();
});

Options

There are a few options that you can pass into the plugin:

  • preview: '.preview',
    Selector for the smaller preview image
  • featureImg: '.feature-image',
    Selector for the larger image
  • indicatorText: 'Drag Me'
    Text for the drag interface

So that’s it. Check out a simple demo and download the plugin. Let me know if you run into any bugs or have any feature requests.

Related Articles