javascripthtmlvariablespts

How can I detect whether the mouse is in a certain part of the screen?


So I'm trying to change the value of a variable based on the Y coordinate of the pointer, and I'm not sure how I would do this. I tried this:

 var righttext = mousemove.clientY;
 switch(righttext){
     case //not sure what to put here
     }

but I wasn't sure what to put in the case. What I want to do is have something like this example: case "top 20% of screen". How would I figure out what the coordinates of the screen are, and then figure out how to use that in a switch statement?

The parts that I want to affect the value are just fifths of the screen divided horizontally.

EDIT:

So I was linked to another post, and found a similar answer to what I was looking for. I changed the code to look like this:

document.addEventListener('mousemove', _.throttle(mouseMoveEventAction, 200));

function mouseMoveEventAction(e) {
	changetext(isInsideThreshold(e.clientY));
}
var rpaneltext = "";

function changetext(isActive) {
  if (isActive) {
      rpaneltext = "awareness";
  } else {
      rpaneltext = "";
  }
}

function isInsideThreshold(cursorY) {
	var threshold = .2;
	var clientHeight = document.documentElement.clientHeight;
  return cursorY > (clientHeight - threshold);
}
But it still doesn't work. Any ideas?

Project here: The part that will be affected by righttext is document.querySelector(".r2").textContent = righttext


Solution

  • You can look at window.innerHeight and window.innerWidth. They return the viewport dimensions.

    You may have better luck with if-else logic like this.

    if (event.clientY < window.innerHeight / 2) {
        // it's in the upper half
    } else {
        // it's in the lower half
    }