Don Munter
Don Munter

Reputation: 633

Automate jquery sliders

I have this example: Click!

With the following jquery:

$(".abox-1").click(function(){
    $("#box-2, #box-3").css({
        zIndex: "-999"
    });
    $("#box-1").css({
        zIndex: "999"
    });
    $("#box-1").stop().animate({
        top: "0%"
    }, 1000, "easeInOutExpo");
    $("#box-2, #box-3").stop().delay(1000).animate({
        top: "100%"
    });
});
$(".abox-2").click(function(){
    $("#box-2").css({
        zIndex: "999"
    });
    $("#box-2").stop().animate({
        top: "0%"
    }, 1000, "easeInOutExpo");
    $("#box-1, #box-3").css({
        zIndex: "-999"
    });
    $("#box-1, #box-3").stop().delay(1000).animate({
        top: "100%"
    });
});
$(".abox-3").click(function(){
    $("#box-1, #box-2").css({
        zIndex: "-999"
    });
    $("#box-3").css({
        zIndex: "999"
    });
    $("#box-3").stop().animate({
        top: "0%"
    }, 1000, "easeInOutExpo");
    $("#box-2, #box-1").stop().delay(1000).animate({
        top: "100%"
    });
});

But, as you can see, this is seriously ugly code! And takes up a lot of space. How can I make a function out of that? Or how do I shorten the code?

Upvotes: 1

Views: 123

Answers (2)

adeneo
adeneo

Reputation: 318172

Maybe something like this ?

$(document).ready(function(){
    $('a[class^="abox"]').click(function() {
        if (this.className == 'abox') {
            $('div[id^=box-]').animate({top: '100%'}, 1000, "easeInOutExpo").css({zIndex: "-999"});
        }else{
            var thisbox = $('#'+this.className.replace('a', '')),
                otherbox = $('div[id^=box-]').not(thisbox);

            otherbox.css({zIndex: "-999"}).stop().delay(1000).animate({top: '100%'});
            thisbox.css({zIndex: "999"}).stop().animate({top: '0%'}, 1000, "easeInOutExpo");
        }
    });
});

FIDDLE

Upvotes: 2

Pavel Strakhov
Pavel Strakhov

Reputation: 40492

You should change classes abox-i to ids aboxi and use the following code:

function show_box(number) {
  for(var i = 1; i <= 3; i++) {
    if (i == number) { // we need to show this element
      $("#box-" + i).css({
        zIndex: "999"
      }).stop().animate({
        top: "0%"
      }, 1000, "easeInOutExpo");
    } else { // we need to hide this element
      $("#box-"+i).css({
        zIndex: "-999"
      }).stop().delay(1000).animate({
        top: "100%"
      });
    }
  }
}

$("#nav a").click(function() {
  var id = parseInt(this.id.substr(4));
  if (id > 0) show_box(id);   
});

JsFiddle

Upvotes: 1

Related Questions