Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

buttons are like one, when i click either button they both do the same thing

why isn't it not working when I press the previous button, it's like both the previous and next button are the same

here's the code: https://codepen.io/pinkypink/pen/NWjzMre

const images = document.querySelector('.carousel_images');
const buttons = document.querySelectorAll('.carousel_button');

const imageCount = document.querySelectorAll('.carousel_images img').length;
let imageIndex = 1;
let translateX = 0;

buttons.forEach(button => {
  button.addEventListener('click', e => {
    if (e.target.id === 'next') {
      if (imageIndex !== 1) {
        imageIndex--;
        translateX += 650;
      }
    } else {
      if (imageIndex !== imageCount) {
        imageIndex++;
        translateX -= 683;
      }
    }
    
    images.style.transform = `translateX(${translateX}px)`;
  });
});
like image 959
Zyndiety Business Avatar asked Feb 02 '26 09:02

Zyndiety Business


1 Answers

Use e.currentTarget not e.target.

e.target is the element that was clicked - in your case the SVG element.

e.currentTarget is the element whose event listener is being called - in your case the div.

like image 110
andrew Avatar answered Feb 03 '26 22:02

andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!