Themeforest

jQuery Image Swap Gallery with Just 3 Lines of Code!

Our earlier post, Quick and Easy jQuery Image Swap has always been popular, so today we are going to use this code to create the ultimate jQuery image swap gallery with just 3 lines of code and 2 lines of CSS.

And here is the jQuery code:

$("#gallery li img").hover(function(){
	$('#main-img').attr('src',$(this).attr('src').replace('thumb/', ''));
});

View The DemoDownload Source Files

A great example of how jQuery can be extremely simple and effective.

The Gallery HTML

All we need for the gallery is the initial, main image and an unordered list holding the image thumbnails.

<div id="gallery">
	<img src="images/gallery/img_1.jpg" alt="" id="main-img" />
	<ul>
	  <li><img src="images/gallery/thumb/img_1.jpg" alt="" /></li>
	  <li><img src="images/gallery/thumb/img_3.jpg" alt="" /></li>
	  <li><img src="images/gallery/thumb/img_4.jpg" alt="" /></li>
	  <li><img src="images/gallery/thumb/img_5.jpg" alt="" /></li>
	  <li><img src="images/gallery/thumb/img_6.jpg" alt="" /></li>
	  <li><img src="images/gallery/thumb/img_7.jpg" alt="" /></li>
	</ul>
</div>

Our thumbnail images have the same file name as the larger versions and these are put into a folder called “thumb”, which is in the same directory as the main images – this is important for our gallery code to work as the image URL is obtained by getting the thumbnail URL and removing the “/thumb”.

Styling The Gallery

Definitely not rocket science here – a total of 2 CSS rules:

#gallery li {
display: inline;
margin-right: 3px;
}
#gallery #main-img {
background: url(images/bg_img.png) no-repeat 0 0;
padding: 26px;
}

Adding Image Preload Function

Although the 3 lines of jQuery will work, we can make the gallery far better if we use our image preload function, from our previous tutorial.

The complete jQuery for the gallery plus preload:

$(document).ready(function() {
	// Image swap on hover
	$("#gallery li img").hover(function(){
		$('#main-img').attr('src',$(this).attr('src').replace('thumb/', ''));
	});
	// Image preload
	var imgSwap = [];
	 $("#gallery li img").each(function(){
		imgUrl = this.src.replace('thumb/', '');
		imgSwap.push(imgUrl);
	});
	$(imgSwap).preload();
});
$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

And that’s basically all there is to it.

Although it may not have fancy fade/zoom/slide/etc effects and look particularly slick, it is a nice and easy example of how to apply the jQuery image swap on hover function.

You can obviously improve on the features but if you are looking for a simple solution without having to understand setting up and styling a complicated gallery plugin (and lets face it some of them are complicated!), then this is about as simple as it gets!

View The DemoDownload Source Files

35 Comments

  • is there way to make the thumbnails a vertical column on right side of main img?
    also, has this been tested on all browsers?

    • Hi,

      Just float the gallery to the right. I have tested in on main browsers

  • Hello !
    I would like to ask you if it is possible to add a zoom button in order to display a biger version of the image.

    Thank you !

  • Hello,
    really helpful tutorial ! Thank you !
    I have a question for you. I’m trying to make it work in my wordpress theme.
    How can I change the code in order to retrieve the url of an image using custom fields ?

    I was thinking something like this:

    <img src="ID,’thumb’,true);?>

    In which fields should iI change the code in order to appear correctly?

    Thank you !
    Nick

    • Hi,

      Unless you were to use AJAX the jQuery code cant retrieve the image URL from a custom field value. The values have to be available on the page so you need to generate the image URL in your theme files

    • Thank you ! I found the solution.

      I would like also to ask you how I could add a button of zoom and a next and previous photo button.

      Is it possible ?

      Thank you !

  • Hi Lee, thanks for your great work.
    I’d like to get work your script without to use an unordered list.

    <div id="wrap">
        <div class="gallery">
            <img ... / >
            <img ... / >
            <img ... / >
        </div>
    </div>
    

    Is it possible? Thanks in advice

    • Hi,

      Instead of using “#gallery li img” you can replace it with “.gallery img”

      • All right! It was another script, that’s why didn’t work.
        Now, i’m thinking how to add captions to the main-img. Do you mind a “clean” way to add captions in this script?
        Really thanks for all your time.

  • Thanks for this, it works brilliantly! I have modified it so it changes the main image on click instead of hover, but am unsure of how to have it change the cursor to the hyperlink one so people know that they are clickable.
    Thanks

    • Hi,

      Use CSS to change the image cursor:

      .img {cursor: pointer;}

      Change the “.img” to the class name you used for the image swap

      • Thanks, that worked great

  • hello

    First off i am no jquery expert, this is pretty much my first attempt at inputting one into a website.

    i’m trying to implement it on
    [/text]http://blog.jewelerformula.com/browngoldsmiths/jewelry/diamonds/

    its looking good however when i hover the thumbnails they don’t swap into the big image like its supposed to. Any help would be greatly appreciated

    • Hi,

      You need to include the scipt inside the $(document).ready() function. So the complete jQuery code would be:

      jQuery(document).ready(function($) {
          $("#gallery li img").hover(function(){
              $('#main-img').attr('src',$(this).attr('src').replace('thumb/', '')).parent().attr('href',$(this).parent().attr('href'));
          });
      });
      
      • Thank You that’s was exactly what it was, Noob mistake. Also thank you for the prompt response, end the headache a little sooner :-)

  • I’m curious about whether or not if in addition to the swap image action, you could make the thumbnails a link to an external page; I haven’t tried building this yet, but the plan is to have a home page with a large image and 4 thumbnails; each of the thumbnails takes the viewer to a new page, but when you hover over them the big image on the home page changes. I presume I should be able to just wrap the img tag with

    <a href="#"><img...></a>

    Just curious if you’d already tried that and if it works.

    Thanks. I love the simplicity of this.

    • Hi,

      It can be added with additional jQuery to swap the href attribute. This can be added by chaining onto the end of the current code that swaps the image src:

      $('#main-img').attr('src',$(this).attr('src').replace('thumb/', ''))
      .parent().attr('href',$(this).parent().attr('href'));
      

      I have uploaded a demo page – jQuery Demo: Ultimate Image Swap Gallery
      with Link

  • This is great; I am using it though for a page with image URLs pulled from a database, so:

    <div id="imageview">
       <img src="<?php echo image_url($filename) ?>" alt="" id="main-img" />
             <ul>
    <?php
        foreach ($images as $image) {
         echo "<li>" . image_view_link($image['filename']) . "</li>";
    } ?>
             </ul>   </div>
    

    How can I make the first image in the list show up as the main image, until one of the other thumbnails is clicked? (Website still in development and not yet posted, so I can’t give you a link.)
    Thank you!

    • Hi,

      Just save the first image filename from the foreach loop as a variable

  • [...] The gallery script I used can be found here [...]

  • !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

    index

  • Hello: I am new to jquery and I really want to use this function, but I cannot seem to get it to work. I am using your all of your codes replacing the source file names with my own, but it is just not working for me. I have downloaded the latest version of jquery. I’m just not sure what I am doing wrong. Any help would be great! Thx!

    • Hi,

      Do you have a link I can take a look at?

      • Thanks for responding! I will just show you what I have:

        HTML:

        index

        CSS
        body{
        margin:0px;
        padding:0px;
        background:#ffffff;
        color:#330033;
        font-family:Verdana, Arial, Helvetica, sans-serif;
        font-size:12px;
        }
        #container {
        width:100%;
        }

        #page {
        width:830px;
        height:549px;
        position:absolute;
        background:url(images/index.jpg) no-repeat;
        z-index:2;
        }

        #gallery li {
        display: inline;
        margin-right: 3px;
        }
        #gallery #main-img {
        background: url(images/bg_img.png)no-repeat 0 0;
        padding: 26px;
        }

        #links{
        position:relative;
        float:left;
        left:5px;
        top:0px;
        margin-bottom:30px;
        width:114px;
        }
        #links a{
        color:#FF9999;
        font-size:14px;
        font-weight:bold;
        font-family:”Trebuchet MS”, Verdana, Arial, Helvetica, sans-serif;
        text-decoration:none;
        display:block;
        border:1px solid #B32D58;
        margin:8px;
        width:112px;
        }

        SCRIPT

        $(”#gallery li img”).hover(function(){
        $(’#main-img’).attr(’src’,$(this).attr(’src’).replace(’thumb/’, ”));
        });

        • HTML(sorry it didnt show up in last post) Thanx for your help!

          index

  • Duh. Just looked at the first post to this. Sorry Lee. Anyway, good tutorial!

    • Hi Mike – the first post will handle individual images but to change an image from groups of images you will need to use the example I gave below

  • Nice! Very simple to use. Any way that we can modify the script to use multiple sets on the same page?

    • Hi Mike – you can change the jQuery image swap gallery code to the following:

      $(document).ready(function() {
      
          // Declare the class name for the gallery container
          var galleryClass = '.gallery';
      
      	$(galleryClass+' li img').hover(function(){
      		var $gallery = $(this).parents(galleryClass);
      		$('.main-img',$gallery).attr('src',$(this).attr('src').replace('thumb/', ''));
      	});
      	var imgSwap = [];
      	 $(galleryClass+' li img').each(function(){
      		imgUrl = this.src.replace('thumb/', '');
      		imgSwap.push(imgUrl);
      	});
      	$(imgSwap).preload();
      });
      $.fn.preload = function() {
          this.each(function(){
              $('<img/>')[0].src = this;
          });
      }
      

      This assumes the our galleries are now wrapped with a div tag using the class name “gallery” and the main image is given the class “main-img” instead of it’s ID.

      To use it just set the gallery class name variable.

      I have uploaded a demo page – Multiple Ultimate Image Swap Galleries

  • i have jquery-1.5.2.min.js loaded but still the same problem.

  • jQuery is new for me i did nothing except having the code from this site and changing the image name.
    how can i load the jQuery library ?

  • i have tried to use the first part of the code as i don’t want the preload function but i get an error message
    $ is not defined

    i have tried this part
    $(document).ready(function() { // Image swap on hover $(”#gallery li img”).hover(function(){ $(’#main-img’).attr(’src’,$(this).attr(’src’).replace(’thumb/’, ”)); });

    the same code for css and html as here

    could you help

    • Hi Mary – is the jQuery library loaded?

  • Can this be done without using ID selectors and only class selectors?

    • Trevor – can change the # selector to use CSS classes no problem. The target image would still need to be unique otherwise you would end up changing all images with that class