-3

I'm trying to apply my code in one simple function with parameters and make it reusable due to the DRY principle. As you can see I use pretty the same code in both of my addEventListener Function. Here is the code that I want to make reusable in my addEventListener function :

 rightBtn.addEventListener("click", () => {
      activeSlide++;
      if (activeSlide > slides.length - 1) {
        activeSlide = 0;
      }
    });

    leftBtn.addEventListener("click", () => {
      activeSlide--;
      if (activeSlide < 0) {
        activeSlide = slides.length - 1;
      }
    });
Amiu
  • 21
  • 7
  • What have you tried so far? Where are you stuck? – Nico Haase Apr 19 '21 at 15:08
  • Except the code for those two functions are not similar. Both perform very different er functions. You could create, for example, use event delegation to target both buttons and have a `handleButton` function, but you'd still basically end up with the same amount of code. – Andy Apr 19 '21 at 15:20
  • Hey (= This is where I stock and don't know what to do! )= – Amiu Apr 19 '21 at 15:20
  • Thank you! (= Now I know how to think! – Amiu Apr 19 '21 at 15:22

2 Answers2

2

You can simply create a function that passes in a value by which you increment or decrement the slide index. And then you can update the slide index as shown in the snippet below.

const slides = ["Apple", "Mango", "Banana"];
let currSlide = 0;

const leftBtn = document.querySelector("#leftBtn");
const rightBtn = document.querySelector("#rightBtn");
const content = document.querySelector("#content");

content.innerText = slides[currSlide];

const changeSlide = (delta) => {
  currSlide = (currSlide + delta + slides.length) % slides.length;
  content.innerText = slides[currSlide];
};

leftBtn.addEventListener("click", () => changeSlide(-1));
rightBtn.addEventListener("click", () => changeSlide(1));
<button id="leftBtn">Left</button>
<span id="content"></span>
<button id="rightBtn">Right</button>
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
1

They only look similar but are completely different.

You can do like this:

const changeSlide = diff => () => {
  activeSlide += diff;
  if (activeSlide < 0) {
    activeSlide = slides.length - 1;
  } else if (activeSlide > slides.length - 1) {
    activeSlide = 0;
  }
  return activeSlide;
};
rightBtn.addEventListener("click", changeSlide(1));
leftBtn.addEventListener("click", changeSlide(-1));