jQuery: image gallery with zoom

We have an image gallery with thumbnails. You click on a thumbnail and a magnifying glass appear, while the thumbnail itself becomes semitransparent. You click on the magnifying glass and the full-sized image appear with a fade in effect. This is a simple effect to achieve with jQuery. Let's dig into the gory details.

We start with the following markup:

<div id="gallery">

	<div class="pic">
		<img src="1.jpg" alt="" />
	<!-- more images -->

Let's add now some styles to keep everything together:

#gallery {
	margin: 0 auto;
	padding: 2em 0;
	height: 550px;
	width: 800px;

div.pic {
	float: left;
	width: 160px;
	height: 110px;
	position: relative;

div.pic img {
	display: block;
	width: 100%;
	height: 100%;
	cursor: pointer;

Each image container has the declaration position: relative on it. Why so? Because of the position of our magnifying glass, that must be horizontally and vertically centered within its container. Let's add now the styles for the magnifying glass and for our full-sized image:

div.pic a.zoom {
	width: 50px;
	height: 50px;
	background: url(zoom.png) no-repeat;
	text-indent: -1000em;
	position: absolute;
	top: 50%;
	left: 50%;
	margin: -25px 0 0 -25px;
	display: none;
	cursor: pointer;

#full {
	clear: both;
	padding-top: 10px;
	width: 800px;
	height: 510px;
	display: none;

Now jQuery. We have to add our full-sized empty image to the gallery, loop through all our thumbnail containers and attach a click event both to the thumbnail image and the link which features the magnifying glass:

$(function() {

  $('<img/>').attr('id', 'full').

  $('div.pic', '#gallery').each(function() {
    var $pic = $(this);
    $('<a/>', {
      'class': 'zoom',
      text: 'Zoom'
    var $a = $('a.zoom', $pic);
    var $img = $('img', $pic);
    $img.click(function() {
        opacity: 0.5
      }, 'slow', function() {
    $a.click(function(event) {
      var src = $img.attr('src');
      $('#full').attr('src', src).fadeIn('slow');
      $img.css('opacity', 1);


When you click on a thumbnail, its opacity is adjusted to 0.5 and the magnifying glass appear. In turn, when you click on this link, the src attribute of the thumbnail is copied into the full-sized image that finally appear with a fade in effect.

Why did you use click?

I used the click event for an usability reason. In fact, this event allows the casual user to get more control over the action he/she wants to perform. On the contrary, a mouseover event is more difficult to master for a user.

You can see the demo below.


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.