Themeforest

jQuery Image Swap Using Click

In a previous post we showed a simple piece of jQuery code, which allows you to add the ability to swap images on hover to your website. Since then we have had several requests asking how to add a similar effect using “click” instead.

The Image

Use the same naming system for the 2 images as in our previous post – i.e. normal state called xxxxxx_off.jpg and the clicked state xxxxxx_on.jpg and add the class “img-swap” to the image tag in your HTML:

<img src="xxxxxx_off.jpg" class="img-swap" />

jQuery Code

With just a few lines of jQuery you can now add the image swap function on click to any images in your web pages:

$(function(){
  $(".img-swap").live('click', function() {
    if ($(this).attr("class") == "img-swap") {
      this.src = this.src.replace("_off","_on");
    } else {
      this.src = this.src.replace("_on","_off");
    }
    $(this).toggleClass("on");
  });
});

See the demo

37 Comments

  • Hi Lee,

    Great script! It’s almost exactly what I’m looking for, but I know nothing about JQuery, so… When you click the button (toggle image on/image off), is it possible to call a different background http page for toggle on/ctoggle off evenents – with resulting page contents results remain hidden?

    Many thanks

    Jamie

    • Hi,

      yes it would be possible although its more advanced than this tutorial covers. I suggest starting with some of the jquery tutorials on the jquery.com site. This should help give you an understanding of how it works

      • Hi – yes it is more advanced, plus I want it to work with multiple toggle buttons on the same page. We are happy to pay for this development. Is this somthing you would be interesting in devoping for us? If so, can you sent us your contact details please.
        Regards
        JamWales

        • Hi,

          Have sent you an email.

          Thanks

  • Hi,

    It should work with all of the latest versions. None of the core jquery events/functions have changed

  • hello, thank for the tut! works great on single button.

    i have 2 image buttons, one toggles a div open and the other toggles it closed.
    im trying to make it where be default the open button is disabled image, and can’t click it, but then when you click the close button the opposite happens, however im having a real hard time achieving this, i can’t seem to get things figured out.

    • Hi,

      Can actually be done fairly easily with just a couple of lines of jquery:

      $('.img-btn.active').live('click',function(){
          $('.img-btn').toggleClass('active');
          $('#test').slideToggle();
      });
      

      Give the 2 images the class “img-btn” and add class “active” to the close button. See demo – http://www.designchemical.com/lab/jquery/demo/jquery_toggle_buttons.htm

      • wohh perfect! thank you. i guess i was just over complicating it by trying to change the image source to a disabled version.

  • great post, almost exactly what i was looking for — how would i modify this to reset the states of other buttons/images to “off” when one is clicked “on”?

    • red previous comments — thanks! :) great site.

  • Hey Lee,

    Thanks for the cool trick.

    I have a scenario that you can possibly look at?

    I have a carousel gallery, and for each I want to add the image swap. if I were to click on an image (image A) and it swapped, is there a way to set up it to if I click on another image (Image B) – then Image A would swap back to the original picture and Image B show its new picture?

    Thanks!
    Jay

    • Sorry about that, read the earlier comments and got it working.

      Thanks!

      Although I have another question…. is it possible to substitute the second swapped image with text?

      Thanks again!

  • Hi Lee,

    Thanks for your post. I have a similar scenario that I can’t quite figure out…

    I’m working on a WordPress site which shows a list of books — and each book has 2 covers (a book cover for the US, and a different book cover for the UK/world).

    I have a DIV with 2 links (US Version and UK Version) — and I’m trying to use jQuery and/or Ajax to switch the cover when you click on each link.

    Here’s a screenshot: http://cl.ly/2W1U1j2k1c1S3q0g3w2m

    I’m getting stuck because I need to call the image using a PHP function, let’s call it “get_image”

    Here’s my code. Can you help?
    HTML:

    <a id="us-cover" href="#">US Version</a> | <a id="uk-cover"href="#">UK Version</a>

    JAVASCRIPT:

    jQuery(function(){
    	 $("#us-cover").live('click', function() {
    		<?php get_image('us'); ?>
    	});
    jQuery(function(){
    	 $("#uk-cover").live('click', function() {
    		<?php get_image('uk'); ?>
    	});
    });
    });
    • Hi,

      There are several ways you can do it. A few examples:

      1. Load both images in the page and then show/hide based on clicked link

      $('#book-1 li a').click(function(e){
      		if($(this).hasClass('version-us')){
      			$('#book-1 img.version-uk').fadeOut();
      			$('#book-1 img.version-us').fadeIn();
      		} else {
      			$('#book-1 img.version-uk').fadeIn();
      			$('#book-1 img.version-us').fadeOut();
      		}
      		e.preventDefault();
      	});
      

      2. Change the image using the “href” attribute of the link to switch the “src” value of the image

      $('#book-2 li a').click(function(e){
      		var src = $(this).attr('href');
      		$('.book-version').attr('src',src);
      		e.preventDefault();
      	});
      

      I think AJAX is maybe a bit of an overkill unless you need to dynamically generate the image in PHP and it cannot be done prior to loading the page. In this case though you cant call the pHP function directly in the jQuery code – you need to do an AJAX POST to a file, which then runs the function.

      The function will return a value (e.g. the image HTML), which can then be used by jQuery to swap the images

      $('#book-3 li a').click(function(e){
                      // In this example we pass a variable using the rel attribute of the link.
      		var rel = $(this).attr('rel');
      
                      // AJAX POST - url of PHP file, any parameters you need to pass then finish off with the callback function if successful
      		$.post('image_function.php', ({version: rel}),function(data){
      			$('#book-3 img').fadeOut().remove();
      			$('#book-3').append(data);
      		});
      		e.preventDefault();
      	});
      

      There are probably many other ways but this should hopefully give an idea of what kind of things you can do.

      I have set up a demo page at the link below so you can also see the source code for each:

      Jquery Demo – Change Image onclick

  • Hi, can you post a menu swap image onclick working example. thanks.

    • Hi – the concept is exactly the same – just add the image swap class to each menu item

  • Lee,

    This helps solve a problem I was having at work, however, I also need a button to change the states of all my buttons “on” and “off.”

    Since I have virtually zero programming skills, I was hoping you could point me in the right direction to accomplish that effect.

    • Hi John,

      You can use the following jQuery code:

      $(function(){
      	$("#btn-swap").click(function(){
      		$('.img-swap').each(function(){
      			if($(this).hasClass('on')){
      				this.src = this.src.replace("_on","_off");
      			} else {
      				this.src = this.src.replace("_off","_on");
      			}
      			$(this).toggleClass("on");
      		});
      	});
      });
      

      All you then need to do is give the button/link that you want to use to toggle the image states an ID of “btn-swap”.

      When clicked this will change any image that has the class “img-swap”. I have uploaded a demo page – jQuery Demo: Multiple Image Swap On Click Button

  • Awesome Les. You are a life saver.

    This blog is great too. Lots of great tutorials!

  • Les, once again, thank you for the reply. I tried out what you put up here straight up like you presented it to me and still nothing. My roll overs are back and working but the swap onclick is not.

    Any thoughts?

    • Rob – you need to remove the first hover event. Only use the one I gave earlier

  • Thanks for the response Lee. I am just not quite getting it though. I tried your code and it does not seem to work. I have none of this defined in the CSS if that makes any difference since these are images and no styling is needed.

    I just want these images to swap on click and mouse over. I am not that great with understanding the jQuery.

    I slightly modified your code and I am getting something to happen with the hovers and clicks but the clicks are off a bit. Hit a few links and let me know what you think.

    I really appreciate the help.

    • Hi Rob – Sorry I just realised I copy/pasted the wrong code from a different file in my earlier reply.

      Use the following instead:

      $(".img-swap:not(.active)").hover(
          function(){this.src = this.src.replace("_off","_on");},
          function(){
              if(!$(this).hasClass('active')){
                  this.src = this.src.replace("_on","_off");
              }
          });
      	$(".img-swap").click(function(){
      		$(".img-swap.active").each(function(){
      			this.src = this.src.replace("_on","_off");
      			$(this).removeClass('active');
      		});
      	$(this).toggleClass('active');
      	});
      
  • Thanks for the quick response… can’t seem to get this one working. It hovers ok, but the onclick takes you to the off image not the on one…

    • James – it sounds like the image does not have the ‘active’ class so it will follow the mouseout event, which is the only part of the code that is able to replace “_on” with “_off”

      Check in firebug whether the image has class “active” after clicking

  • Hi, did anyone have an answer to JW regarding resetting all the images if another image is clicked. Like a radio button would.. I’m fairly new to jQuery and can’t seem to work it out… thanks

    • James – see earlier comment

  • This is great, I used the image swap on hover and it works perfectly. I am trying to get this to work with a click also but cannot seem to get it working. Can anyone see what I am doing wrong?

    http://bridgfordfoodservice.net/ready_to_eat/products.php

    It is suppose to work on the left hand menu that changes the product. You can see that it hovers but does no stay when the link is clicked.

    • Hi Rob – probably not the most elegant solution but this should work:

      $(".img-swap:not(.active)").hover(
          function(){
              this.src = this.src.replace("_off","_on");
          },
          function(){
              this.src = this.src.replace("_on","_off");
          });
          $(".img-swap").click(function(){
              $(".img-swap.active").each(function(){
                  this.src = this.src.replace("_on","_off");
                  $(this).removeClass('active');
              });
               $(this).toggleClass('active');
          });
      
  • Works great – than kyou so much! Just one question, is there a way to turn the cursor into a pointer on mouseover? How would you do that in JQuery? Thanks a lot!

  • Is there something I need server side for this to work? I can’t seem to get this to work when I test this locally.

    btw, I’ve never used js or jquery before so I may be missing something basic

    • James – nothing required server-side. You do need the jQuery library loading first though. Make sure the following code is included in the head of the document before the jQuery code:

      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
      
  • Just wanted to say thanks for posting this. Exactly what I needed. Will definitely be adding your feed to my list.

    • Thanks. Glad it helped

  • Thanks for the nice script. If you have a string of images, how would you script it so that clicking on one image would swap that image, but clicking on a second image would swap the first image back while swapping the second image?

Leave a comment

To add code to your comments wrap the code text in [text][/text] tags