skip to Main Content

prev_btn and next_btn are the functions it triggered when someone click the buttons

let i = 0;

function prev_btn() {
  console.log("Previous button Clicked");
  i--;
  if (i < 1) {
    i = 5;
  }
  console.log(i);
  preview();
}
function next_btn() {
  console.log("Next button Clicked");
  i++;
  if (i > 5) {
    i = 1;
  }
  console.log(i);
  preview();
}

function preview() {
  let img = document.getElementById("slider_img").setAttribute("src", `Slider/img${i}.jpg`);
}

Just want to make slider and its working but I need better way to do this

2

Answers


  1. Although you have not post what exactly you want and i do not have your code to get the concept of you script. I think hereby you can make your current code more dynamic.

        let i = 0;
    const slidesNum = document.getElementById('slideHolder').childNodes.length;
    
    function prev_btn() {
      console.log("Previous button Clicked");
      i--
      if(i > 1 ){
        i = slidesNum
      }
      console.log(i)
    }
    function next_btn() {
      console.log("Next button Clicked");
      i++
      if(i > slidesNum){
        i = 1
      }
      console.log(i)
    }
    
    Login or Signup to reply.
  2. the correct and classic way to do that:

    const
      imgElm  = document.querySelector('#image-element') 
    , imgList = ['17','37','19','30','22']  // from https://picsum.photos/
    , len     = imgList.length
      ;
    let indx = 0
      ;
    setImg()
      ;
    function setImg() 
      {
      imgElm.src = `https://picsum.photos/id/${imgList[indx]}/300/200`;
      }
    function prev_btn()
      {
      indx = (--indx + len) % len; // indx = ((indx - 1) + len) % len;
      setImg();
      }
    function next_btn() 
      {
      indx = ++indx % len;  // indx = (indx + 1) % len;
      setImg();
      }
    <img id="image-element" src="" >
    <br>
    <button onclick="prev_btn();">prev</button>
    <button onclick="next_btn();">next</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search