Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle between 3 classes using toggleclass

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.

like image 765
Sana Joseph Avatar asked Dec 01 '22 22:12

Sana Joseph


1 Answers

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];
});
like image 166
Fabrizio Calderan Avatar answered Dec 04 '22 12:12

Fabrizio Calderan