2

this is my code: I want to change the img src by clicking on the button and add one to the counter that change the next photo again But only the first photo is displayed ! and I have 8 img in this path : images/slides/writing${0-7};

slider = () =>{
    let i=0;
      let slides = document.getElementById('slides').getElementsByTagName('img')[0];
    slides.src = `images/slides/writing${i}.jpg` ; 
    i++
    
   
}
  
<section id="slides">
        <picture>
          <img src="" alt="Slide img">
          <input type="button" value="change" onclick="slider()">
      </picture>
 </section>

1
  • 1
    You reset i = 0 every time slider() is called (and it's a new variable every time because you declare it locally with let). Move this line outside of the function: let i=0; Commented Jul 4, 2020 at 20:31

1 Answer 1

2

You are always setting i to 0 inside the function, just make it global and make sure it doesn't exceed 7:

let i=0;
slider = () =>{
    if(i==8) i=0;
    let slides = document.getElementById('slides').getElementsByTagName('img')[0];
    slides.src = `images/slides/writing${i}.jpg` ; 
    i++
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.