let leadTracker = [];
const inputText = document.getElementById("input-text");
const inputButton = document.getElementById("input-button");
const Listing = document.getElementById("listings");
inputButton.addEventListener("click", function () {
leadTracker.push(inputText.value);
clicker();
});
function clicker() {
for (let i = 0; i < leadTracker.length; i++) {
Listing.innerText += leadTracker[i];
console.log(leadTracker);
}
}
I added bro to the array and then back but bro is repeated. This is exactly the same code I read online but it is still not working fine for me.
You have to ways to do this : first you have to not use for loop in the function
function clicker() {
Listing.innerText += leadTracker[leadTracker.length-1];
console.log(leadTracker);
}
or you can remove all innerText from the element then re-write it again :
function clicker() {
Listing.innerText = "";
for (let i = 0; i < leadTracker.length; i++) {
Listing.innerText += leadTracker[i];
console.log(leadTracker);
}
}
Each time you click the button you take the content of the text field and add it to the leadTracker array. So the array grows with each click, longer and longer. So far so good.
But in the the clicker function, which also runs on every click, you take the entire content of the array and append it to Listing. They array is not cleared in between clicks, so old items in it will be printed again.
You can either skip using an array at all:
inputButton.addEventListener("click", function () {
Listing.innerText += inputText.value;
});
or replace the inner text of Listing instead of appending it, as suggested in other answers.
Each time you call clicker it's going to add the whole array to Listing, including stuff that's already there.
Did you mean to clear out Listing at the beginning of clicker, before the for loop?
Listing.innerText = ""