Search code examples
jquerycssaddclassremoveclass

CSS & jQuery (Q1): Best light-weight method to switch from slide to slide on click


I create small animated graphics using CSS and jQuery. There are a series of animations which switch from slide to slide when you click on a button.

I currently use this method:

<script>
$(function() {
$("#z-tab1").click(function() {
$(".zSlide1").removeClass("zhide");
$(".zSlide2").removeClass("zshow");
$(".zSlide3").removeClass("zshow");

//hide previous slides
$(".zSlide1").addClass("zshow");
$(".zSlide2").addClass("zhide");
$(".zSlide3").addClass("zhide");

</script>
<style>
.zhide{ display:none; }
.zshow{ display:block;}

/*slide 1 */
.zSlide1 {
width:100%;
height:100%;
max-width:600px;
min-height:500px;
min-width:320px;}

Is there a better way to achieve this?

Thanks in advance ;)


Solution

  • You can do something like this:

    // set an active slide to display when page loads $('.elem1').addClass('activeSlide');

    // count your elements(which class name starts with "elem") and push them into an array
    var 
    elems = 0,
    i = 1;
    
    $('[class^="elem"]').each(function(){
        elems +=1;
    });
    
    // display one element at a time, by modifying the z-index value
    $('.button').on('click', function(e){
        e.preventDefault();
        i+=1;
        if(i > elems ){ i = 1; };
        $('[class^="elem' + i + '"]').addClass('activeSlide').siblings().removeClass('activeSlide');
    });
    



    Example here: http://jsfiddle.net/WrQ4L/1/

    Keep in mind that this method requires to have class names numbered ascending(the initial value of "i" is equal to the first class number -> elem1)