Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a jquery carousel from scratch

I know there are a ton of questions on here about jquery image carousel, but they all refer to a plugin. I would like to make one from scratch. It's a pretty simple one, there are 2 buttons, one left and one right. when you click the left button, the position of the overall container that has all the images shifts to the left, and the right makes it go right.

This is what I have so far... Right now the problem is only the left button works. (the right button works only once you slide the image to the left once) And I also want it to animate across all the images, and go to the last image when you get to the end of the set of images

JS:

total_entries = $("image-entry").length;
var current_index = 0;
var slider_entries = $('#slider-entries');

$('#home-slider #left').click(function(){
    go_to_index(current_index-1);
    return false;
});

$('#home-slider #right').click(function(){
    go_to_index(current_index+1);
    return false;
});



var go_to_index = function(index){
    if(index < 0)
        index = total_entries - 1;
    if(index > total_entries - 1)
        index = 0;
    if(current_index == index)
        return;



    var left_offset = -1 * index * 720;
    slider_entries.stop().animate({"left": left_offset}, 250);
    //description_container.stop().animate({"left":left_offset}, 250);
    current_index = index;
};

HTML:

<div id="slider">
    <div id="slider-entries">
        <div class="image-entry">
            <img src="http://placekitten.com/720/230" />
        </div>
        <div class="image-entry">
            <img src="http://placedog.com/720/230" />
        </div>
        <div class="image-entry">
            <img src="http://placedog.com/720/230" />
        </div>
    </div>
</div>

total width of each image is 720px total with of slider-entries is

Thanks

like image 741
Bill Avatar asked Feb 12 '26 20:02

Bill


1 Answers

You have a problem with the total_entries variable. First of all you need a "var" in front, to define that it's a new variable. Second, you forgot a "." (dot) to search for the class in your HTML code..

your first line should be:

var total_entries = $(".image-entry").length;

Hope it works ;-)

like image 139
Simon Avatar answered Feb 14 '26 09:02

Simon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!