jQuery: mosaic gallery

A mosaic gallery is a simple CSS image gallery where every single image is put in a specific position within a container. To achieve this effect, we'll use absolute positioning by placing the very first image on the center of the gallery and other four images on its corresponding four corners. jQuery will be used to animate this gallery with a fading effect that will progressively show each image and then collapse them all. Of course you can get more interesting CSS effects if you make your images overlap and use CSS3 transformations. Here's our CSS:

#gallery {
 width: 600px;
 height: 500px;
 position: relative;
 margin: 0 auto;

#gallery img {
 width: 260px;
 height: 160px;
 display: none;
 position: absolute;

#gallery #img1 {
 top: 50%;
 left: 50%;
 margin: -80px 0 0 -130px;

#gallery #img2 {
 top: 0;
 left: 0;

#gallery #img3 {
 top: 0;
 right: 0;

#gallery #img4 {
 bottom: 0;
 left: 0;

#gallery #img5 {
 bottom: 0;
 right: 0;

Our jQuery code, instead, requires in this case the use of a singleton (galled Gallery) which has a sole public method for handling the gallery animations. Every other property is kept private, because there's no need to make them publicly available outside our object:

 var Gallery = new function() {
    var images = $('img', '#gallery');
    var len = images.length;
    var index = -1;
    var limit = len;
    this.animate = function() {
      setTimeout(function() {
        var img = images.eq(index);
        if(index == limit) {
          index = -1;
        setTimeout(arguments.callee, 1500);
      }, 50);

The public animate() method (bad name, I know, because it leads to possible conflicts with the core jQuery's method) simply creates a timer which enters into an infinite loop by calling itself. When it runs, it first increments its internal counter up to 5 (the length of our image set) and then it resets that counter to -1 and starts again. In the meantime, it uses its counter as an index to select all the images using the eq() method and fade them into view. When it reaches its limit, the animation simply hides all the images. And so on. You can see the demo below.


Live demo

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

One thought on “jQuery: mosaic gallery”

Leave a Reply

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