K
K
KononovD2019-03-07 19:05:58
JavaScript
KononovD, 2019-03-07 19:05:58

What needs to be fixed in order for a self-written js slider to work?

Hello, we have the following code
https://codepen.io/Kononov_D/pen/GeWBbN?editors=1010
I wanted to practice js, I decided to write my own slider, awry, but I wrote it, sat happy)
then I thought: "what, if I want 2 or more sliders to my page? copy-paste the code?"
I thought about it and decided to put my slider in a class, so that I could work with instances of this class later.
And here's the problem:
creating an instance, passing parameters, initializing the slider - everything is fine ...
and then, the fields that I created in the constructor and in the console of an error like "Cannot read property 'click' of undefined" seem to be removed from the instance
Moreover, I can hang an event on buttons - I can, they are, but when it comes to clicking on these buttons - they are no longer in the variables ... what should I do?
The codePen below also has a working, non-OOP (functional) version.
by the way, how to pass an object to the constructor?)
it is likely that I messed up somewhere with the call context, but if you remove this. - swears that the variable is not found ..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stockholm Syndrome, 2019-03-07
@KononovD

when you attach handlers to elements, for example, here:
the context is lost, so you need this:
he is lost here too.

this.autoplayInterval = setInterval(function() {
  this.sliderNext.click();
}, this.sliderDelay);

so either use an arrow function:
this.autoplayInterval = setInterval(() => {
  this.sliderNext.click();
}, this.sliderDelay);

or again the bind method:
this.autoplayInterval = setInterval(function() {
  this.sliderNext.click();
}.bind(this), this.sliderDelay);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question