jQuery: dividing image effect

Dividing an image with jQuery is an effect that we can achieve in a relatively easy way. We need a container to host the main image, CSS absolute positioning, a CSS rule to hide the thumbnails by default and a single loop to create such thumbnails. First of all, let's define our markup.

<div id="image">

 <img src="1.jpg" alt="" id="main" />

</div>

Now we need first some basic CSS rules:

#image {
 width: 500px;
 height: 333px;
 margin: 0 auto;
 position: relative;
}

#image #main {
 width: 100%;
 height: 100%;
 display: block;
}

position: relative will create a contextual positioning for our thumbnails. Now we need to generate them:

$(document).ready(function() {

  var src = $('#image #main').attr('src'), i, len = 5;
  
  for(i = 1; i < len; i += 1) {
  
    $('<img/>').attr({
      src: src, 
      width: 125, 
      height: 85, 
      id: 'thumb-' + i
    }).appendTo('#image');
  
  
  }
  // code continues
  
});

We've assigned a progressive ID to all the thumbnails. Since now the thumbnails are visible, we need to hide and position them with CSS:

#image #thumb-1,
#image #thumb-2,
#image #thumb-3,
#image #thumb-4 {
 position: absolute;
 width: 125px;
 height: 85px;
 display: none;
}

#image #thumb-1 {
 top: 0;
 left: 0;
}

#image #thumb-2 {
 top: 0;
 right: 0;
}

#image #thumb-3 {
 bottom: 0;
 left: 0;
}

#image #thumb-4 {
 bottom: 0;
 right: 0;
}

Our thumbnails have been positioned on each corner of the main container box. Then we need to show them after a certain time delay:

// code continues

var interval = window.setTimeout(function() {
  
  
    $('#main').animate({
      opacity: '0.5'
    }, 1000, function() {
    
    
      $(this).nextAll().show(1000);
    
    });
  
  
}, 2000);

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.