user298519 user298519 - 7 months ago 13
Javascript Question

JQuery: How to display an array of paragraph tags one by one on each click?

var sentences = ['sentenceone', 'another sentence', 'another sentence again'];

$(".btn").on('click', function() {

for(var i=0; i < sentences.length; i++) {
samplebox.innerHTML += '<p>'+sentences[i]+'</p>';
}
});


This displays all of them in one click. How do I fix this?

Answer

You can displays the paragraphs one by one like this :

var sentences = ['sentenceone', 'another sentence', 'another sentence again'];
var i = 0;

$(".btn").on('click', function() {

  if (i < sentences.length) {
    samplebox.innerHTML += '<p>' + sentences[i] + '</p>';
    i++;
  }

});