Home > OS >  How do I continue a mouse click function after scrolling down the page?
How do I continue a mouse click function after scrolling down the page?

Time:11-29

I am trying to create an interactive website which allows the user to click anywhere on the page and the text will show up in that exact mouse location. However when I scroll down the page the onclick function doesnt use the exact mouse location and appears elsewhere. How would I continue this function after scrolling down the page?

const texts = [
  "Paragraph: 1",
  "Paragraph: 2",
  "Paragraph: 3",
  "Paragraph: 4",
  "Paragraph: 5",
  "Paragraph: 6",
  "Paragraph: 7",
  "Paragraph: 8",
  "Paragraph: 9",
  "Paragraph: 10"
];
const classes = [
  "red gray-bg font-1",
  "blue font-2",
   "red",
  "blue",
   "red",
  "blue",
   "red",
  "blue",
   "red",
  "blue",
  
];
// 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];


  //set its position and position style
  div.classList=classes[currentParaIdx];
  div.style.position = "absolute";
  div.style.left = clientX   "px";
  div.style.top = clientY   "px";
  currentParaIdx  ;
  document.body.append(div); //add div to the page
});

This code all works apart from when I scroll down the page. If anyone knows how to do this, it would be much appreciated.

CodePudding user response:

Try this, adding the window scroll pos

div.style.top = (clientY   window.scrollY)   "px";
  • Related