Often used as part of an image gallery or to show additional information, again this can be done in javascript by gradually changing the padding of elements. This often looks choppy on mobile devices, and frames can be missed if the animation is quick. CSS transitions plus transforms help out to make this a simple effect to create.

Have a look at a more complete example on the demos page.

Demo 1 - Sliding by translating the images (transitions and transforms)

Note: Animating by transitioning transforms is hardware accelerated on iOS, making this a good option there.

Plan

  1. Create a container with overflow set to hidden.
  2. Inside that container, create another container with width equal to the width of all the images added together.
  3. Inside that, float the images left with no padding or margin.
  4. When clicking a control, translate the second container to show the required image.

Demo

Image 1Image 2Image 3Image 4

Code

The CSS looks like this:

#slide1_container {
  width:450px;
  height:281px;
  overflow:hidden; /* So the sliding bit doesn't stick out. */
  margin:0 auto;
}
#slide1_images {
  /* This is the bit that moves. It has 4 images, so 4 * 450 = 1800. You could use javascript
  to work this out instead by counting images. */
  width:1800px;

  -webkit-transition:all 1.0s ease-in-out;
  -moz-transition:all 1.0s ease-in-out;
  -o-transition:all 1.0s ease-in-out;
  transition:all 1.0s ease-in-out;
}
#slide1_images img {
  padding:0;
  margin:0;
  float:left; /* All the images are in a row next to each other. */
}

The rather simple JS looks like this. (Note that jQuery 1.8+ does the vendor prefixes for you here.

$(document).ready(function() {
  $('#slide1_controls').on('click', 'span', function(){
    $("#slide1_images").css("transform","translateX("+$(this).index() * -450+"px)");
    $("#slide1_controls span").removeClass("selected");
    $(this).addClass("selected");
  });
});

It should be fairly obvious, but you could easily change this by changing the translateX to translateY if you lay the images out differently, or by changing opacity instead to create an image fader.

Adding a next or previous button requires you to keep track of which image is currently showing, then adjust the transform.

Comments/Questions?

Please add any questions/corrections/extra info below. Please be courteous to other users.

blog comments powered by Disqus

avenue-origin