Hedra
Hedra

Reputation: 89

Replace numbers by a calculation in Javascript

I would like to know if there's a way in javascript to replace [0] by a calculation : [+1] and [-1]

Example of my situation :
I have a gallery presenting 6 images, I want to use keyboard arrows to navigate.
When the current image is the 4th, if I let [1] in my script to go to the previous image by pressing keyboard arrow, the first image appears instead of the third.
Any idea ? Thanks.

Script :

$(document).on('keyup', function (e) {
    switch (e.which) {
        case 37:
            $('.prev')[0].click();
            break;

        case 39:
            $('.next')[0].click();
            break;
    }
});

Upvotes: 0

Views: 58

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You need to store current position

var current = 0;
$(document).on('keyup', function (e) {
    switch (e.which) {
        case 37:
            $('.prev')[--current].click();
            break;

        case 39:
            $('.next')[++current].click();
            break;
    }
});

Upvotes: 1

Related Questions