Search code examples
javascriptinputuser-input

How would I detect clicks in javascript?


I'm building a little web game in node.js, and I've been using event listeners for input, and it's worked fine for things like key presses and mouse movement.

window.addEventListener("keydown", onKeyDown);
window.addEventListener("keyup", onKeyUp);
window.removeEventListener("mousemove", onMouseInput);

(all of these have worked perfectly)

But when I tried using the mouseup/mousedown events (and also pointerup/pointerdown), they won't register. Is there something I'm doing wrong? Does it have to click on something?

window.addEventListener("pointerdown", changeShooting(true));
window.addEventListener("pointerup", changeShooting(false));

(doesn't work)


Solution

  • You have to pass a function to addEventListener, while you are passing the result of the call to changeShooting (which I assume does not return a function).

    In order to do that, you can define an inline function like:

    window.addEventListener("pointerdown", function() {
      changeShooting(true)
    });
    

    If you need to remove the listener later, you have to define it explicitly:

    function onPointerDown() {
      changeShooting(true);
    }
    
    window.addEventListener("pointerdown", onPointerDown);
    
    // later somewhere
    window.removeEventListener("pointerdown", onPointerDown);