A
A
Alexey Dzyuba2017-11-10 19:43:16
JavaScript
Alexey Dzyuba, 2017-11-10 19:43:16

Self-written OOP slider in javascript - why an error (closures)?

I'm trying to make my slider in oop style. Here is the code:

spoiler
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);


I want to make it possible to specify my own control buttons in the constructor. And in the body of the function, I wrote .onclick, but I'm afraid that's where the error lies. Something with closures? Here is the error:
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

1 answer(s)
E
eRKa, 2017-11-10
@Alex_Dz

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 question

Ask a Question

731 491 924 answers to any question