I have a button and empty div in HTML.
<button id="add_sentence">Click here!</button>
<div id="parent"></div>
In JS, I have data in array
let data = [{ sentence: "Hi, I'm from Azerbaijan" }, {sentence: "I'm 36 years old"}, { sentence: "I learn front-end development}]
I need a function that when I click on button ("#add_sentence"), it takes only one sentence from array ("data") and adds to div ("#parent").
I can add all array to empty div with 1 click. But I want 1st click adds 1st sentence. Then, 2nd click adds 2nd sentence. 3rd click adds 3rd sentence and so on.
Can anyone help?
CodePudding user response:
let data = [{ sentence: "Hi, I'm from Azerbaijan" }, {sentence: "I'm 36 years old"}, { sentence: "I learn fron-end development"}];
const button = document.querySelector("#add_sentence");
const parent = document.querySelector("#parent");
let clickCount = 0;
button.addEventListener('click', () => {
if (clickCount < data.length) {
const nextSentence = document.createElement('p');
nextSentence.innerText = data[clickCount].sentence;
parent.appendChild(nextSentence);
clickCount ;
}
})
<button id="add_sentence">Click here!</button>
<div id="parent"></div>
CodePudding user response:
In the example below, the AddSentence() method is assigned to the onclick attribute in the <button> element. Each time the <button> element is clicked, the first sentence is selected in order from the data array and inserted into the <div> element. If the control variable is more than the number of data array elements, it is set to 0 again.
let data = [
{ sentence: "Hi, I'm from Azerbaijan" },
{ sentence: "I'm 36 years old"},
{ sentence: "I learn fron-end development" }
];
let control = 0;
function AddSentence()
{
parentElement = document.getElementById('parent');
parentElement.innerHTML = data[control ].sentence;
if(control >= data.length)
control = 0;
}
<button id="add_sentence" onclick="AddSentence()">Click here!</button>
<div id="parent"></div>
CodePudding user response:
Without clickcount...
var data = [{ sentence: "Hi, I'm from Azerbaijan" }, {sentence: "I'm 36 years old"}, { sentence: "I learn front-end development"}],
prnt = document.getElementById("parent"),
bttn = document.getElementById("add_sentence");
bttn.addEventListener("click", _ => data.length && (prnt.textContent = `${data.shift().sentence}
`));
#parent { white-space: pre;
}
<button id="add_sentence">Click here!</button>
<div id="parent"></div>
