Home > Blockchain >  Get VW/VH position from onclick event in JS
Get VW/VH position from onclick event in JS

Time:03-01

This code will give me the x and y value of the click in pixels:

document.getElementById("game").addEventListener("click", function(event) {
   console.log(event.clientX, event.clientY);
});

But how do I get the X and Y values comparitive to VH (Viewport Height) and VW (Viewport Width) (I want to get the value like how in CSS you can set an element to be 20vh [20% of viewport height] etc etc)

CodePudding user response:

Did you mean something like this ?

You just need to get the innerWidth and innerHeight from the window element than compute the percentage with a cross product

(elementX * 100) / viewport width
(elementY * 100) / viewport heght

document.getElementById("game")
  .addEventListener("click", function(event) {
    const debug = document.getElementById('debug');
    const clickX = event.clientX;
    const clickY = event.clientY;
      
    const vh = window.innerHeight;
    const vw = window.innerWidth;
  
    const ratioX = (clickX * 100) / vw;
    const ratioY = (clickY * 100) / vh;
  
    debug.innerHTML = '';
    debug.append(`X:${clickX}  Y:${clickY}`);
    debug.append("\n");
    debug.append(`%X:${ratioX} %Y:${ratioY}`);

  });
body {
  background-color: lemon;
  display: flex;
  width: 100vw;
  height: 100vh;
  flex-flow: column;
  justify-content: center;
  align-items: center;
}

#game {
  background-color: cyan;
  width: 29.7vw;
  height: 21vh;
  box-shadow: 0px 0px 2px rgba(0,0,0,.6), 0px 0px 6px rgba(0,0,0,.3);
}
<div id=game></div>

<pre id=debug>
  X:   Y:
  %X: %Y: 
</pre>

CodePudding user response:

You first need to get the Viewport Width (vw) by using window.innerWidth and Viewport Height (vh) by using window.innerHeight.

Then, divide the event.clientX by vw and multiply by 100 to get value in percentages. Same logic to get Y co-ordinates, i.e. divide the event.clientY by vh and multiply by 100 to get value in percentages.

See my demo below: (Click on Game to get the co-ordinates)

let gameEl = document.getElementById("game"),
  eCXinVWEl = document.getElementById("eCXinVW"),
  eCYinVHEl = document.getElementById("eCYinVH");

gameEl.addEventListener("click", function(event) {
  let vw = window.innerWidth,
    vh = window.innerHeight,
    eCXinVW = event.clientX / vw * 100, // Multiplying by 100 to get percentage 
    eCYinVH = event.clientY / vh * 100; // Multiplying by 100 to get percentage 

  console.log(eCXinVW, eCYinVH);

  eCXinVWEl.innerHTML = eCXinVW;
  eCYinVHEl.innerHTML = eCYinVH;
});
.box {
  padding: 50px;
}

#game {
  padding: 20px;
  background: red;
}
<html>

  <head>
  </head>

  <body>
    <div >
      <h6>Event co-ordinates X by viewport width: <span id="eCXinVW">0</span>%</h6>
      <h6>Event co-ordinates Y by viewport height: <span id="eCYinVH">0</span>%</h6>

      <div id="game">Game</div>
    </div>
  </body>

</html>

  • Related