window.onload = function(){
new Slider({
images: ".slider__galary img",
btnPrev: ".btnPrev",
btnNext: ".btnNext",
rate: false
})
}
function Slider(obj){
this.images = document.querySelectorAll(obj.images);
this.btnPrev = obj.btnPrev;
this.btnNext = obj.btnNext;
this.rate = obj.rate;
this.time = obj.time || 1000;
var self = this;
var i = 0;
this.prev = function(){
self.images[i].classList.remove("showed");
i--;
if(i < 0){
i = self.images.length - 1;
}
self.images[i].classList.add("showed");
}
this.next = function(){
self.images[i].classList.remove("showed");
i++;
if(i >= self.images.length){
i = 0;
}
self.images[i].classList.add("showed");
}
document.querySelector(this.btnPrev).onclick = this.prev;
document.querySelector(this.btnNext).onclick = this.next;
if(this.rate){
setInterval(this.next, this.time);
}
}
class Slider {
constructor({images, btnPrev, btnNext, rate, time}) {
this.images = document.querySelectorAll(images);
this.btnPrev = btnPrev;
this.btnNext = btnNext;
this.rate = rate;
this.time = time || 1000;
this.counter = 0;
document.querySelector(this.btnPrev).onclick = this.prev.bind(this);
document.querySelector(this.btnNext).onclick = this.next.bind(this);
if (this.rate) {
setInterval(this.next.bind(this), this.time);
}
}
prev() {
this.images[this.counter].classList.remove("showed");
this.counter--;
if (this.counter < 0) {
this.counter = this.images.length - 1;
}
this.images[this.counter].classList.add("showed");
}
next() {
this.images[this.counter].classList.remove("showed");
this.counter++;
if (this.counter >= this.images.length) {
this.counter = 0;
}
this.images[this.counter].classList.add("showed");
}
}
// мне кажется, что ждать полной загрузки страницы тут незачем
document.addEventListener('DOMContentLoaded', () => {
new Slider({
images: ".slider__galary img",
btnPrev: ".btnPrev",
btnNext: ".btnNext",
rate: false
});
});
// хелпер для прослушивания событий
class EventListener {
constructor(ctx, handlers, target) {
this.ctx = ctx;
this.handlers = handlers;
Object.keys(handlers).forEach(event => target.addEventListener(event, this));
}
handleEvent(event) {
const {handlers, ctx} = this;
const {type} = event;
if(typeof handlers[type] !== 'function') return;
handlers[type].call(ctx, event);
}
}
class Slider {
construnctor({images, btnPrev, btnNext, rate, time = 1000}) {
this.images = document.querySelectorAll(images);
this.i = 0;
new EventListener(this, {
click: this.prev
}, document.querySelector(btnPrev));
new EventListener(this, {
click: this.next
}, document.querySelector(btnNext));
if(rate) {
setInterval(() => this.next(), time);
}
}
prev() {
this.images[i].classList.remove("showed");
this.i--;
if(this.i < 0){
this.i = this.images.length - 1;
}
this.images[i].classList.add("showed");
}
next() {
this.images[i].classList.remove("showed");
this.i++;
if(this.i >= this.images.length){
this.i = 0;
}
this.images[i].classList.add("showed");
}
}