Lorraine Bernard
Lorraine Bernard

Reputation: 13400

How to make an image slider in javascript

I am implementing an image slider in javascript/jquery.

The demo should work like this. http://londatiga.net/tutorials/scrollable/
Anyway I don't won't to rely on jquery.tools.min.js because this lib is out of date (the last update is about 8 months ago ).
I decide to make the js code by me.

When clicking on next or prev button I would like to shift the images on the list of one item/image. The script shifts the items but the display is quite crappy, because the next items is not displayed.

The list is made of 4 images. At the beginning only the first two images are displayed, then when clicking on the next button I would like to display the second and the third image.

Actually the script shows just the first and the second image even if I click on the next button.

Here is the demo: http://jsfiddle.net/xRQBS/5/ Here is the code (1)

Any hints how should I fix it? thanks

(1)

/*global jQuery */
(function ($) {

    var imgs = [
    'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSsarNmO4Vdo5QwHfznbyxPmOyiYQ-KmBKUFsgEirvjW6Kbm7tj8w',
    'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRfIAfLXj3oK1lso1_0iQploSKsogfJFey3NnR0nSD9AfpWjU7egA',
    'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR1dO4FVDDitdS85aLOCsOpQyHHTysDhD4kHQ749bMtNxaj5GMKnA',
    'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRAPO77sVu-Xk80S_txagySoTq8gKHgeiS63a9TYtKbPpGYVI5X'
    ];

    var $list = $('.list-images');

    var $slider = $('.slider');

    var slideImage = function (direction) {
        var unit = 150;
        var left = parseInt($slider.attr('left'), 10) || 0;

        left = (direction === 'prev') ? left - 150 : left + 150; 

        $slider.css('left', left + 'px'); 

    };

    $(function () {
        $.each(imgs, function (i, img) {
            $list.append($('<li>').append($('<img>').attr('src', img)));
        });

        $('body').on('click', '.direction', function () {
            slideImage($(this).attr('data-tid'));
        });
    });


}(jQuery));
​

Upvotes: 2

Views: 1433

Answers (2)

MKS
MKS

Reputation: 352

I'm assuming that you want the shift to be more of an animation. If so, take a look at jQuery's animate. Something like this:

$slider.animate({left: left + 'px'});

That will give it a sliding effect, which what I'm assuming you want :)

Upvotes: 1

John Moses
John Moses

Reputation: 1283

With the animate function:

$slider.animate({'left': left + 'px'}, 1000);

http://jsfiddle.net/xRQBS/6/

Upvotes: 1

Related Questions