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

Leave a Reply