Propozycja poprawek
const xz = $('.s').width();
let i = 0;
$('.btn-right').click(function () {
if (i < $('.s').length - 1)
{
i++;
$('.slide').css('transform', `translatex(-${(i * xz)}px)`);
} else {
i = 0;
$('.slide').css('transform', 'translatex(0px)');
}
});
$('.btn-left').click(function () {
if (i > 0)
{
i--;
$('.slide').css('transform', `translatex(-${(i * xz)}px)`);
} else {
i = $('.s').length - 1;
$('.slide').css('transform', `translatex(-${(i * xz)}px)`);
}
});
wersja 1 DRY
const xz = $('.s').width();
let i = 0;
$('.btn-right').click(function () {
move_slide('forward');
});
$('.btn-left').click(function () {
move_slide('backward');
});
function move_slide(cmd) {
if (cmd == 'forward') {
if (i < $('.s').length - 1) {
i++;
} else {
i = 0;
}
} else { // backward
if (i > 0) {
i--;
} else {
i = $('.s').length - 1;
}
}
$('.slide').css('transform', `translatex(-${(i * xz)}px)`);
}
wersja 2 DRY
const xz = $('.s').width();
let i = 0;
$('.btn-right').click(function () {
move_slide(); // move_slide(1); // forward
});
$('.btn-left').click(function (){
move_slide(-1); // backward
});
function move_slide(step = 1) {
i += step;
if (i > $('.s').length - 1) {
i = 0;
} else if (i < 0) {
i = $('.s').length - 1;
}
$('.slide').css('transform', `translatex(-${(i * xz)}px)`);
}
wersja 2.1 DRY
const xz = $('.s').width();
const FORWARD = 1, BACKWARD = -1;
let i = 0;
$('.btn-right').click(function () {
move_slide(FORWARD);
});
$('.btn-left').click(function () {
move_slide(BACKWARD);
});
function move_slide(step) {
i += step;
if (i > $('.s').length - 1) {
i = 0;
} else if (i < 0) {
i = $('.s').length - 1;
}
$('.slide').css('transform', `translatex(-${(i * xz)}px)`);
}
Tak jak @Wiciorny napisał zapomniałeś
Zgubiłeś w warunku ostatnim, przy zerowaniu, transform
$(slide).css('transform', 'translate(0px)');
Polecenie
$('.s').width(), // Zwraca szerokość pojedynczego elementu o klasie s
$('.s').length); // Zwraca ilość elementów o klasie s
console.log($('.s').width(), $('.s').length);