I am creating an interactive website which consists of multiple paragraphs gradually being displayed once the user clicks anywhere on screen. I want these paragraphs put into an array and then displayed in the order that they are set. When a user clicks screen - show paragraph 1, when a user clicks screen again - show paragraph 2 and so on while keeping them all on the screen.
However I am not sure how to combine both these elements in javascript, I have the EventListener function working but how would I go about displaying the array. In a for loop etc? If anyone knows how to do this it would be greatly appreciated.
document.addEventListener("click", (e) => {
const { clientX, clientY } = e; //get the click position
//create the div
const div = document.createElement("div");
//set its text
div.innerText = "text";
//set its position and position style
div.style.position = "absolute";
div.style.left = clientX "px";
div.style.top = clientY "px";
document.body.append(div); //add div to the page
});
How would I incorporate the array paragraphs on each click one by one?
CodePudding user response:
You just need an Active Tracker Variable
const texts = [
"Paragraph: 1",
"Paragraph: 2",
"Paragraph: 3",
"Paragraph: 4",
"Paragraph: 5",
"Paragraph: 6",
"Paragraph: 7",
"Paragraph: 8",
"Paragraph: 9",
"Paragraph: 10"
];
// Keeps Track of Current Text
let currentParaIdx = 0;
document.addEventListener("click", (e) => {
// Stop once All Texts are Displayed
if (currentParaIdx === texts.length) return;
const {
clientX,
clientY
} = e; //get the click position
//create the div
const div = document.createElement("div");
//set its text
div.innerText = texts[currentParaIdx];
currentParaIdx ;
//set its position and position style
div.style.position = "absolute";
div.style.left = clientX "px";
div.style.top = clientY "px";
document.body.append(div); //add div to the page
});