jQuery toggle to change image

hejog picture hejog · Jun 30, 2009 · Viewed 53.6k times · Source

I have a list of divs with images in them:

<div class="wizard-img"><%= image_tag("sources/pix/nyt.png") %></div>
<div class="wizard-img"><%= image_tag("sources/pix/theguardian.png") %></div>

When a user clicks the div, I'd like it to change the image to x-on.png, when clicked again, it'll change to x-off.png, and when clicked a third time it should revert to x.png.

Is it possible to do this without manually specifying jQuery for every image change? Can I traverse the div and find the image name, and simply append the -off/-on to the image?

Thanks!

Answer

nikc.org picture nikc.org · Jun 30, 2009

Perhaps CSS sprites would work for you?

That would save you from loading a separate image every time you click the image (button?), and you could solve your problem by adding and removing a css-class, e.g.:

$('.wizard-img').click(
    function() {
        if ($(this).hasClass('on')) {
            $(this).removeClass('on').addClass('off');
        } else if ($(this).hasClass('off')) {
            $(this).removeClass('off');
        } else {
            $(this).addClass('on');
        }
    }
);