jQuery: image replacement gallery

In this post I'm going to show you how to create an image gallery using an image replacement technique to allow users to view the enlarged version of a series of thumbnail images. We'll work with the href attributes of thumbnail links and with the src attribute of the main image. Let's start with our markup structure:

<div id="gallery">

  <div id="pic">
    <!-- large image here-->
  </div>
  
  <ul>
  
    <li>
      <a href="path/to/large/img">
        <!-- thumbnail img here-->
      </a>
    </li>
    
    <!--more thumbnails-->
  
  </ul>

</div>

Now a couple of CSS styles to make our gallery look how we want:

#gallery {
 width: 480px;
 margin: 0 auto;
}

#gallery ul {
 height: 100%;
 overflow: hidden;
 margin: 0;
 padding: 0;
 list-style: none;
}

#gallery ul li {
 float: left;
 width: 120px;
 margin: 0;
}

#gallery ul li a {
 float: left;
 display: block;
 margin: 0;
 width: 100%;
}

#gallery ul li a img {
 border: none;
 display: block;
 width: 100%;
}

#gallery #pic {
 width: 100%;
 height: 300px;
 border-bottom: 10px solid silver;
}

#gallery #pic img {
 display: block;
 width: 100%;
 height: 100%;
}

When a user clicks on a link, the main image is replaced with the enlarged version of each thumbnail. Also, we want to add a transition effect during this change:

$(document).ready(function() {
  
  $('#gallery ul li').each(function() {
  
    var $li = $(this);
    var $a = $li.find('a');
    var href = $a.attr('href');
    
    $a.click(function(e) {
    
      $('#pic img').animate({
        opacity: 0,
      }, 1000, function() {
      
        $(this).attr('src', href).animate({
          opacity: 1
        }, 1000);
      
      });
      
      e.preventDefault();
    
    
    });
  
  
  });
  
});

We copy the path to each full image from the href attribute of each link and we use it on the src attribute of the main image. 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.