javascriptcssdomaddeventlistenerviewport-units

Get VW/VH position from onclick event in JS


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)


Solution

  • 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 class="box">
          <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>