Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JQuery to change order of elements

Does anybody know what I'm doing wrong? I'm trying to alter the order on which some images show, I want the images to shift to the right/left one spot every time I hit a button. This is what I've tried but no luck.

Any help or insight will be truly appreciated

$("#rightShift").click(function(){
    $("img").hide();
    var count = $("img").size();
    $("img").each(function(i) { 
        var indexImg = count - i;
        $("img:eq(indexImg)").show();
    });
}); 
$("#leftShift").click(function(){
    $("img").hide();
    $("img:last").prependTo("img");
    $("img").show();
});
like image 465
user1204301 Avatar asked Feb 11 '12 20:02

user1204301


1 Answers

Assuming you want this to work like a carousel that goes around (the last image become the first one when you are shifting right), then this is how I would do it:

$("#rightShift").click(function(){
    $("img:last").detach().insertBefore("img:first");
});

$("#leftShift").click(function(){
    $("img:first").detach().insertAfter("img:last");
});
like image 119
Diego Avatar answered Sep 27 '22 17:09

Diego