4

I have 3 images that I want to switch between. I put each one of them in a class & change it's image in the css. I can now switch between 2 classes but when I add the third one the code doesn't work. Any class of them can be the starting one.

    $('.one').click(function(){                             
        $(this).toggleClass("two");
        $(this).toggleClass("one");

    });
     $('.two').click(function(){                             
        $(this).toggleClass("one");
        $(this).toggleClass("two");

    });

When I add this line:

        $(this).toggleClass("three"); 

It doesn't toggle at all....

Do you know a method in which I can put all of them in one function ?

Thanks.

Sana Joseph
  • 1,948
  • 7
  • 37
  • 58
  • 1
    could you make a practical example of what are you trying to accomplish and which is the desired result? – Fabrizio Calderan Jun 05 '12 at 08:54
  • The user has an X pic for example green, when he clicks on it, it should be yellow, when he clicks on it, it should be red. If the image was already red, it should be green then yellow , If he started with a yellow one, it should be red then green then yellow ... & so on. – Sana Joseph Jun 05 '12 at 09:01
  • 1
    so you need to make a sequential cycle of class assignments, right? – Fabrizio Calderan Jun 05 '12 at 09:03

3 Answers3

14

Example fiddle: http://jsfiddle.net/KdfEV/

This code will allow you to cycle through a sequence of defined classes

$('.one, .two, .three').click(function() {                             
    this.className = {
       three : 'one', one: 'two', two: 'three'
    }[this.className];
});
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • 1
    Would it be possible if I asked you what this "[this.className];" makes ? It's working & everything but I can't understand what it does. – Sana Joseph Jun 05 '12 at 10:12
  • 2
    it's used as lookup through the keys of the object `{ three : 'one', one: 'two', two: 'three' }`. E.g. when current class is `two` this construct will look inside the object for this key and will pick its associated value (three) changing the className of the element – Fabrizio Calderan Jun 05 '12 at 10:27
4
$('.one, .two, .three').click(function(){                             
        $(this).toggleClass("one, two, three");
    });
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • Thanks .. But when I try it here http://jsfiddle.net/OnlyHope/qbZ9q/1/ It just toggles two classes, what about the third one ? – Sana Joseph Jun 05 '12 at 09:17
0

The safest way would be to remove unwanted classes and add the required class:

// Switch to class 'three'
$(this).removeClass('one').removeClass('two').addClass('three');
Tim
  • 6,281
  • 3
  • 39
  • 49