For a school project i'm coding a slideshow and the javascript part should use object oriented programming - I've a method "nextSlide" that switch between image to animate the carrousel and I want the animation to perform automatically every 5 seconds :
I've tried the following code but it doesn't seems to work,
var diaporama = {
slides : document.querySelectorAll('#slides .slide'),
currentSlide : 0,
nextSlide : function() {
slides[currentSlide].className = 'slide';
currentSlide = (currentSlide+1)%slides.length;
slides[currentSlide].className = 'slide showing';
},
slideInterval : function() {
setInterval(this.nextSlide(), 5000)
}
}
diaporama.slideInterval();
The animation doesn't perform and Firefox give me the following error : SyntaxError: expected expression, got ':' SyntaxError: missing formal parameter
Edit : I found a way to make it work by tweeking my code like this:
nextSlide : function() {
this.slides[this.currentSlide].className = 'slide';
this.currentSlide = (this.currentSlide+1)%this.slides.length;
this.slides[this.currentSlide].className = 'slide showing';
}
}
var myVar = setInterval("diaporama.nextSlide()", 5000)
how the code is for a OOP school project, I think you could use better OOP way to write your code:
class Diaporama { constructor(containerSelector, itemSelector, interval) { var _containerSelector = containerSelector; var _itemSelector = itemSelector; var _interval = interval; var _slides = document.querySelectorAll(selector); var _currentSlide = 0; setSlideInterval(); } get slides() { return this._slides; } set slides(value) { this._slides = value; } get currentSlide() { return this._currentSlide; } set currentSlide(value) { this._slid_currentSlidees = value; } get containerSelector() { return this._containerSelector; } get itemSelector() { return this._itemSelector; } get interval() { return this._interval; } nextSlide() { slides[currentSlide].className = this.itemSelector; currentSlide = (currentSlide + 1) % slides.length; slides[currentSlide].className = this.itemSelector + ' showing'; } setSlideInterval() { setInterval(this.nextSlide(), this.interval); } } //instance var mySlide = new Diaporama('#slides', '.slide', 5000);
Here is are reference to javascript classes: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
The get
syntax binds an object property to a function that will be called when that property is looked up (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)
The set
syntax binds an object property to a function to be called when there is an attempt to set that property (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set)