Basically I want to render a div next to where I click. I have done that works perfectly but my problem is when I scroll down its not following and render relevant to the page and not the screen. Any work around my code if this so far:
const [position, setPosition] = useState([0,0])
const renderGuess = (event) =>{
if(guessed){
setPosition([0,0]);
setGuessed(false);
}else{
setPosition([event.clientX, event.clientY]);
setGuessed(true);
}
}
function Guess (position){
const {location} = position
console.log(location)
return(
<div id="guess-div" style={{top: `${location[1]}px`, left: `${location[0]}px`}}>
Note: I'm using react the render works fine only problem is when I scroll down it renders for example 150px from the top of the page not 150px from the screen. I have tried 150 / 10, with vh and vw.
CodePudding user response:
The event.clientX
and event.clientY
will get the viewport coordinates, not the document coordinates as you want.
You can replace the
setPosition([event.clientX, event.clientY]);
by
setPosition([event.pageX, event.pageY]);
to get the coordinates relative to the entire document instead.
References: