Krishna Sai
Krishna Sai

Reputation: 301

Check if a mouse is pressed at the upper half or lower half of the screen in JavaScript

I want a pure JavaScript solution

This is what I am doing. I hope you get the clear idea:

  1. What I am basically trying to do here is to make my player move up if I press and hold the upper half of the screen and similarly the lower half too.
  2. But I am unable to figure out the correct way to solve this issue. I don't know what logic have I messed up.
  3. have searched many solutions online but all are using jQuery and I don't want to use that unnecessarily for this simple task.
let isdown = false;
    document.addEventListener("mouseup", () => {
        iddown = false;
    });
    document.addEventListener("mousedown", () => {
        isdown = true;
    });
    document.addEventListener("mouseover", (event) => {
        if (isdown) {
            console.log("I am here");
            let middlehalf = window.innerHeight / 2;
            console.log(middlehalf, event.offsetY);
            if (e.offsetY > middlehalf) {
                playerPos += 20;
            } else {
                playerPos -= 20;
            }
        }
    });

summary:

  1. To be able to handle mouse press and hold events.
  2. To be compatible with mobile devices.
  3. To be able to differentiate where the mouse event occurs. (Either the upper half or the bottom half).
  4. Pure JavaScript solution.

Upvotes: 1

Views: 1301

Answers (1)

xy2_
xy2_

Reputation: 7162

When you use offsetY, you get the coordinates relative to the parent, here the document. If you scroll down, then the coordinates will shift down as well. You can use clientY, which gives you the coordinates in the viewport, relative to the screen itself.

document.addEventListener("mouseover", (event) => {
    if (isdown) {
        let middlehalf = window.innerHeight / 2;
        if (e.clientY > middlehalf) {
            playerPos += 20;
        } else {
            playerPos -= 20;
        }
    }
});

Upvotes: 3

Related Questions