'create a carousel than can go backwards and forwards on button click

Im selecting all image's with a query and then displaying them 2 at a time with "style.display = 'inline'; " and hide the privious image with style.display = 'none'. When i get to the last picture, i want to set the index back to 0, so you can keep on going through pictures in a carousel. The same for the back button, but there is something wrong with how the if statement is doing its arithmetic and im lost in the code as it is right now.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <script
             src="https://code.jquery.com/jquery-3.6.0.js"
             integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
             crossorigin="anonymous"></script>

   <title>Document</title>
   <style>
   img {
       display:none;
       width:25%;
   }


   </style>
</head>
<body>
   <div>
       <img class="slidepic" src="https://picsum.photos/200/300">
       <img class="slidepic" src="https://picsum.photos/200/290">
       <img class="slidepic" src="https://picsum.photos/200/280">
       <img class="slidepic" src="https://picsum.photos/200/270">
       <img class="slidepic" src="https://picsum.photos/200/260">
       <img class="slidepic" src="https://picsum.photos/200/250">
     </div>
     <button class="btnback" id=”btnback”>Back</button>
     <button class="btnnext" id=”next”>Next</button>



<script>
const images = document.querySelectorAll("img");

let i = 0;

   document.querySelector('.btnnext').addEventListener('click', ()=>{  

  
       if(i == 0) {
           images[i].style.display = 'inline';
           images[i+1].style.display = 'inline';
         } else if(i == images.length ) {
           images[i + 1].style.display = 'none';
           images[0].style.display = 'inline';
           i = 0;
         } else {
           images[i - 1].style.display = 'none';
           images[i].style.display = 'inline';
           images[i+1].style.display = 'inline';
         }
         
        i++;
      
   });
 

   
   document.querySelector('.btnback').addEventListener('click', ()=>{  

  
       if(i > 0) {
           images[i].style.display = 'inline';
           images[i-1].style.display = 'inline';
         } else if(i == 0 ) {
           i = images.length ;
           images[i + -1].style.display = 'none';
           images[i].style.display = 'inline';
          
         } else {
           images[i+1].style.display = 'none';
           images[i].style.display = 'inline';
           images[i-1].style.display = 'inline';
         }
         
        i++;
      
   });


</script>

</body>
</html>



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source