I Have problem when using for and show data with append. Scrolling down and add 7 letters every time when user scroll to the bottom but when letters finish it gives me two more undefined i don’t know how to fix it. I tried break but without anything new.

Can you help me please. Thank you

var x = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

var xLength = x.length;

for (var i = 0; i < 7; i++) {
  $("#testDiv").append(`
    <p>` + i + ` : ` + x[i] + `</p>
  `);
}

window.onscroll = function() {
  if (window.scrollY > (document.body.offsetHeight - window.outerHeight)) {
    console.log("It's working!");
  }
}

window.onscroll = infiniteScroll;
var isExecuted = false;

function infiniteScroll() {
  if (window.scrollY > (document.body.offsetHeight - window.outerHeight) && !isExecuted) {
    isExecuted = true;
    var fromItem = $("#testDiv").children().length;

    for (var i = fromItem;
      (i < fromItem + 7) && (xLength > fromItem); i++) {;
      $("#testDiv").append(`
        <p>` + i + ` : ` + x[i] + `</p>
      `);
    }

    setTimeout(() => {
      isExecuted = false;
    }, 1000);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="testDiv"></div>

Answer

var x = [...'abcdefghijklmnopqrstuvwxyz']
for (var i = 0; i < 7; i++) {
  if(x[i]){$("#testDiv").append(`<p>${i+1}: ${x[i]} </p>`);}
}

window.onscroll = infiniteScroll();
function infiniteScroll() {
    var fromItem = $("#testDiv").children().length;
    for (var i = fromItem; i <= x.length; i++) {                 
      if(x[i]){$("#testDiv").append(`<p>${i+1}: ${x[i]} </p>`);}
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="testDiv"></div>

I made the code a little more readable and fixed the problem using a if statement

Write a comment

Your email address will not be published. Required fields are marked *