javascripthtmlarraysonclickslice

How to display 3 elements by 3 of an array in HTML using array.sclice() method in javascript


I have found a way to display a portion of an array using arrayName.slice(start, end), i made a funtion to feed the start and end to the slice method so i can use it with onClick button to click next 3 element to show in HTML.

my problem is the increment funcion doesn't start with zero(0), it start with 3- 6, and when i press next it start from 6 - 9. it is working proberly but not starting from zero

    const array = ["a1","a2","a3","a4","a5","a6","a7","a8","a9","a10","a11","a12","a13","a14","a15"]

let next = {
        start: 0,
        end: 0,
        incrementby: 3,
        inc() {
          this.start = this.start = 0 ? 0 : this.start + this.incrementby;
          this.end = this.start + this.incrementby;
          console.log(this.start, this.end);
          displayHadith(this.start,this.end)
        },
      };
      
 function displayHadith(start,end) {
        var container = document.querySelector(".container");
        container.innerHTML = ""
        let some = array.slice(start, end);
         for (let element of some) {
          container.innerHTML +=`
          <div class="sharh" >${element}</div>
          `
         }
        }
<button onclick="next.inc()">clickNext</button>
<div class="container"></div>


Solution

  • Add incrementby to start after changes:

    const array = ["a1","a2","a3","a4","a5","a6","a7","a8","a9","a10","a11","a12","a13","a14","a15"]
    
    let next = {
      start: 0,
      end: 0,
      incrementby: 3,
      inc() {
        this.end = this.start + this.incrementby;
        console.log(this.start, this.end);
        displayHadith(this.start,this.end);
        this.start += this.incrementby;
      },
    };
          
     function displayHadith(start,end) {
      var container = document.querySelector(".container");
      container.innerHTML = ""
      let some = array.slice(start, end);
      for (let element of some) {
        container.innerHTML +=`
        <div class="sharh" >${element}</div>
        `
      }
     }
    <button onclick="next.inc()">clickNext</button>
    <div class="container"></div>