JavaScript left and right button function

This is for the HTML5 canvas game I'm doing. In the game there is a character who has a gun, he can shoot it and reload. I would like the player to use the left mouse button to shoot and the right mouse button to reboot.

What I need is that when I press the left mouse button, the variable in my player object (Player1.isLeftClick) becomes true, and when I release the button, the same variable becomes false. The same thing should happen with the right mouse button, but with a different variable (Player1.isRightClick). I also want it to work with all the most popular browsers (Chrome, Firefox, Explorer, etc.). I should also be in pure JavaScript without libraries like jQuery! I have already achieved this with keyboard events, but I need this with mouse events.

If this helps, I already have event handlers for the keyboard up and down and mouse movements. They are executed in the init function, which initializes the game when loading images.

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

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

+4
source share
1 answer

You want to use the e.button property to check which mouse event is e.button . Left click value is different in IE . Your code will 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

+12
source

All Articles