I have written some code as an object to fade in and out some images, only when I call for the slideshow to be build, I am getting an
"Uncaught ReferenceError: imgArray is not defined".
Can anyone help as to why I am getting this error. Thank you.
const slideShow = {
curIndex: 0,
imgDuration: 10000,
slider: document.querySelector('.banner__slider').childNodes,
imgArray: [
'images/background/img3.jpg',
'images/background/img1.jpg',
'images/background/img2.jpg'
],
buildSlideShow(arr) {
for (i = 0; i < arr.length; i++) {
const img = document.createElement('img');
img.src = arr[i];
slider.appendChild(img);
}
},
slideShow() {
function fadeIn(e) {
e.className = "fadeIn";
};
function fadeOut(e) {
e.className = "";
};
fadeOut(slider[curIndex]);
curIndex++;
if (curIndex === slider.length) {
curIndex = 0;
}
fadeIn(slider[curIndex]);
setTimeout(function () {
slideShow();
}, imgDuration);
},
};
slideShow.buildSlideShow(imgArray).slideShow();
You are getting the error because there is no imgArray variable in the code. You could change this to:
slideShow.buildSlideShow(slideShow.imgArray).slideShow();
This fixes one issue but creates another one. The buildSlideShow method doesn't return anything. So, .slideShow() method will again throw an error. Since, imgArray is a property of slideShow object, you can make use of the this keyword. Change the method to:
buildSlideShow() {
for (i = 0; i < this.imgArray.length; i++) {
const img = document.createElement('img');
img.src = this.imgArray[i];
slider.appendChild(img);
}
return this;
}
From the buildSlideShow, return the instance of the object by using return this. This way you can chain the methods.
const slideShow = {
curIndex: 0,
imgDuration: 10000,
// slider: document.querySelector('.banner__slider').childNodes,
imgArray: [
'images/background/img3.jpg',
'images/background/img1.jpg',
'images/background/img2.jpg'
],
buildSlideShow() {
console.log("inside buildSlideShow method");
for (i = 0; i < this.imgArray.length; i++) {
console.log(this.imgArray[i]);
const img = document.createElement('img');
img.src = this.imgArray[i];
//slider.appendChild(img);
}
return this;
},
slideShow() {
console.log("inside slideShow method")
}
}
slideShow.buildSlideShow()
.slideShow();
(I have commented out the slider code)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With