0

I'm having problem while implementing load more using JavaScript. Can anyone please help?

I've tried using for loops. As I'm a beginner to JavaScript, I was able to implement a little.

<script>

  let ar = ['a', 21, 'b'];
  let postToShow = 1;
  function load(val) {

    for (let i = 0; i < ar.length; i++) {

      if (postToShow % (ar.length + 1) !== 0) {
        document.getElementById('num').innerHTML += ar[postToShow - 1] + "<br />";
        postToShow++;
        return;
      }
    }
  }

</script>

<body>
  <button onclick="load()" id="loadMore">Load more </button>
</body>

I expect output to be loaded based on postToShow. Please help...

3
  • Hello, Dante. You can create code snippet with triple ` or ~ Commented Jul 15, 2019 at 6:43
  • You don't have to add backticks in every line. Paste your code -> Select it -> Click on {} in the editor to format it Commented Jul 15, 2019 at 6:47
  • Ok Adiga will do Commented Jul 15, 2019 at 6:59

1 Answer 1

1

A for loop is not really an ideal solution here given that you want to add content one by one, ie. there is no need to iterate over the content every time.

A more simple solution would be to keep track of some sort of a counter and grab the content from the array that way.

You can try something like this

<ul id="content-wrapper"></ul>
<button onclick="load()" id="loadMore">Load more </button>

const content = ['a', 'b', 'c', 'd', 'e', 'f'];
let counter = 0;

function load() {
  var node = document.createElement("li");  // Create a <li> node
  var textnode;

  if(content[counter]) {
    // Create a text node if there is text  
    textnode = document.createTextNode(content[counter]); 
  } else {
    // Return a message if there is no more
    textnode = document.createTextNode('No Data'); 
  }

  counter++; // Increment counter
  node.appendChild(textnode);  // Append the text to <li>
  document.querySelector('#content-wrapper').appendChild(node)
}

Codepen here.

Let me know if you need any further help with this.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @BornaS for the immediate reply. But I need to show content based on postToShow. For example if I change postToShow to 2, It has to show 2 posts from the array
Sorry for the misunderstanding, did see the formatted code when I was writing the answer. You can see an updated version on this codepan: codepen.io/BornaSepic/pen/agregm, let me know if it works according to your wishes .
Thank you @BornaS for ur effort. It was the answer i was looking for. Works simply great :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.