Answer the question
In order to leave comments, you need to log in
Self-written OOP slider in javascript - why an error (closures)?
I'm trying to make my slider in oop style. Here is the code:
var prevBtn = document.querySelector('.btn-prev--js');
var nextBtn = document.querySelector('.btn-next--js');
var sliderImgs = document.querySelectorAll('.slider-img');
var i = 0;
function Slider(images, prevBtn, nextBtn) {
this.images = images;
this.i = 0;
prevBtn.onclick = function () {
hide(this.images[this.i], 19);
this.i--;
if (this.i < 0) {
this.i = this.images.length - 1;
}
show(this.images[this.i], 19);
};
nextBtn.onclick = function () {
hide(this.images[this.i], 19);
this.i++;
if (this.i > this.images.length - 1) {
this.i = 0;
}
show(sliderImgs[this.i], 19);
}
}
var mySlider = new Slider(sliderImgs, prevBtn, nextBtn);
common.js:47 Uncaught TypeError: Cannot read property 'undefined' of undefined
at HTMLButtonElement.Slider.nextBtn.onclick (common.js:47)
Answer the question
In order to leave comments, you need to log in
function Slider(images, prevBtn, nextBtn) {
var self = this;
this.images = images;
this.i = 0;
prevBtn.onclick = function () {
hide(self.images[self.i], 19);
self.i--;
if (self.i < 0) {
self.i = self.images.length - 1;
}
show(self.images[self.i], 19);
};
nextBtn.onclick = function () {
hide(self.images[self.i], 19);
self.i++;
if (self.i > self.images.length - 1) {
self.i = 0;
}
show(sliderImgs[self.i], 19);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question