Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch images with addEventListener in JavaScript without Jquery

I am trying to switch images with addEventListner. I can do it with arrays, but trying to test with event listener, but having problems with it.

HTML:

<img id="previous" style="left: 0">&lt;</img>
<img id="mainImg" src="https://res.cloudinary.com/vaqar/image/upload/v1499825595/DSC_0015_b0hr2j.jpg"></img>
<img id="next" style="right: 0">&gt;</img>

JavaScript:

const slider = [
    {
       imgSrc: "https://res.cloudinary.com/vaqar/image/upload/v1499826226/DSC_0361_y3mv4r.jpg",
   },
   {
       imgSrc: "https://res.cloudinary.com/vaqar/image/upload/v1499826238/DSC_0360_sfwyqh.jpg",

   },
   {
       imgSrc: "https://res.cloudinary.com/vaqar/image/upload/v1499826221/DSC_0303_esrlla.jpg",
   },
];

 var i = 0;

 var sliderImg = document.querySelector("mainImg");
 sliderImg.addEventListener('click', function(e){
       e.src = e[i+1].imgSrc;
       ++i;
 });
like image 859
user6642297 Avatar asked Mar 05 '26 21:03

user6642297


1 Answers

The event of a click event is not the object itself, but an Event object. You'll need to access the target property to set src.

e.target.src

Also, you're trying to use array syntax on the Event rather than on the Array itself. e[i+1].imgSrc isn't really anything. There's a few strategies you can take to properly cycle through the array of images. One would be to keep track of the current index of your image in the array and increment it with each click. I think that's the direction you were headed based on the i variable.

Note: be careful of scoping inside a click event handler. this scope has changed unless you're in a situation where you can use arrow functions.

// Your array is overly complex
const slider = [
  { imgSrc: "https://res.cloudinary.com/vaqar/image/upload/v1499826226/DSC_0361_y3mv4r.jpg" },
  { imgSrc: "https://res.cloudinary.com/vaqar/image/upload/v1499826238/DSC_0360_sfwyqh.jpg" },
  { imgSrc: "https://res.cloudinary.com/vaqar/image/upload/v1499826221/DSC_0303_esrlla.jpg" },
];

 var sliderImg = document.querySelector("mainImg");
 sliderImg.addEventListener('click', function(e){
       i++;
       // test if you've exceeded the array limits and loop back to 0.
       if (i === slider.length) {
            i = 0;
       }       
               // use slider here
       e.target.src = slider[i].imgSrc;

 });
like image 154
James Tomasino Avatar answered Mar 07 '26 10:03

James Tomasino



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!