How is it possible to convert mouse vertical/horizonta position to width (px) JavaScript?

54 Views Asked by At

Having the dynamically changed mouse position I'm trying to convert it to width pixels, making it 0px if the mouse is at the bottom of the screen and 100px if the mouse is at the top frame of the screen, how is it possible in js? Probably I would need a regular converting expression. Maybe I also would need an if statement?

let posY = 0.23       // received from the outer function
const el = document.querySelector(".el")

el.style.width = (posY*2 ...) + 'px',  //trying to write this line, make it wider if posY > 0, more narrow if posY < 0 relatively 

1

There are 1 best solutions below

1
o q On

I imagine it would be something like this:

document.addEventListener('DOMContentLoaded', () => {
  const MAX_WIDTH = 100;
  const viewportHeight = (window.innerHeight || document.documentElement.clientHeight);
  const elBar = document.querySelector('.bar');
  const elInfo = document.querySelector('.info');

  window.addEventListener('mousemove', (event) => {
    const width = parseInt(((viewportHeight - event.offsetY) / viewportHeight) * MAX_WIDTH);
    elBar.style.width = `${width}px`;
    elInfo.innerHTML = `Width: ${width}px`;
  });
});
.bar {
  background: red;
  display: inline-block;
}
<div class="bar">&nbsp;</div>
<div class="info">Try to move your mouse here</div>

Try to move around your mouse above the snippet, up and down. It should show you the translated size in pixel according to the mouse position on the viewport.