Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display array elements individually after mouse click

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading