Web Freelancer

Carousel with variable image widths

I have been struggling to find right image carousel built on top of jQuery. Trend with these kinds of plugins is to have as many features as possible but somehow I wasn’t able to find the one I needed. I was looking for scrolling with different image widths.

I am on my own now. I am looking for simplest solution possible which I am to build on my own.

Step 1: HTML/CSS only

As a starting point I use simple DIV element with overflow:auto parameter. You can view live Example 1 as well. Sample code structure will look like this:

<div>
  <ul>
    <li><img src="../public/img/image1.jpg" height="150" alt=""></li>
    .
    .
    n
  </ul>
</div>
<style type="text/css" media="screen">
.carousel ul { overflow:auto; white-space:nowrap; margin:0; padding:0; list-style:none; }
.carousel li { display:inline-block; }
</style>

Step 2: Let’s add some JavaScript

Well we have simplest carousel possible but perhaps we don’t won’t it to be that simple. Let’s add few simple controls for scrolling to next and previous page as seen in Example 2.  Hide that ugly scrollbar by setting overflow:hidden. The controls will simply scroll the view by one width of carousel.

By adding some more functionality we accomplish scrolling by one image. The trick is simple. Just find first positive position of all the elements inside the list and scroll to it’s position. Getting backwards is the same. Find last negative position. That’s it. We don’t need to forget to set position:relative to list. Reason, we don’t want to get offsets of our elements counted from the top left corner of the whole page. See Example 3 for demonstration.

Step 3: Make it prettier

Unfortunately there’s one problem with our current solution. When scrolling by one page forward or backwards, sometimes (a lot) your images end up cut. One solution would be to scroll by one image forward/backwards but we want something more usable.

I decided to drop our current scroll-by-one-page script and clone one for scroll-by-one-image script and adjust it a little. Instead of finding next/previous image I grab carousel’s width and find last visible (and possibly cut) element.

Demo

Take look at live Examle 4 with source code included.

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>