5

This is for an HTML5 canvas game that I am making. In the game, there is a character that has a gun, he can shoot it and reload it. I would like the player to use the left mouse button for shooting and the right mouse button for reloading.

What I need is that when ever I click the left mouse button, a variable in my player object(Player1.isLeftClick) becomes true, and when I let go of the button the same variable becomes false. The same thing should also happen with the right mouse button, but with another variable(Player1.isRightClick). I also want it to be capable with all the most popular browsers(Chrome, Firefox, Explorer, etc.). I must also be in pure JavaScript with no libraries like jQuery! I already achieved this with keyboard events, but I need this with the mouse events.

If it helps, I already have event handlers for keyboard up and down and mouse movement. These are made in the init function that initializes the game when the images are loaded.

document.addEventListener('mousemove', mousePos, false);
document.addEventListener('keydown', checkKeyDown, false);
document.addEventListener('keyup', checkKeyUp, false); 

I also have variable called mie that is true if the used browser is Internet Explorer and false for other browsers.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
JeremeiBou
  • 61
  • 1
  • 1
  • 5

1 Answers1

13

You want to use the e.button property to check which mouse event was called. The value for the left mouse button being clicked is different in IE. Your code would look like this:

var left, right;
left = mie ? 1 : 0;
right = 2;

document.body.addEventListener('mousedown', function (e){
    if(e.button === left){
        Player1.isLeftClick = true;
    }
    else if(e.button === right){
        Player1.isRightClick = true;
    }
}, false);

document.body.addEventListener('mouseup', function (e){
    if(e.button === left){
        Player1.isLeftClick = false;
    }
    else if(e.button === right){
        Player1.isRightClick = false;
    }
}, false);

Demo

Some Guy
  • 15,854
  • 10
  • 58
  • 67
  • 2
    jsfiddle: Uncaught ReferenceError: mie is not defined – Kroid Feb 11 '16 at 13:32
  • 1
    @Kroid, yeah. You need to populate it via your favourite IE detection way. Check out [some of them](http://stackoverflow.com/questions/4169160/javascript-ie-detection-why-not-use-simple-conditional-comments) – hypers Oct 01 '16 at 16:52
  • You can simplify the code by only checking if the button is right (2). If it's not right, then it's the left button. – SingleStepper Apr 23 '17 at 20:36
  • @SingleStepper That's not true - mice commonly also have a clickable scroll button (and occasionally others too, for gaming mice). You ought to test for equality for conditions instead of testing for inequality and inferring it. – Some Guy Apr 24 '17 at 08:57