0

I noticed that these function doesn't work good in Firefox, but does in Chrome.

I use these function in a game in Js to shoot bullet (left mouse click) and to create a fireball all around the player with the right click that burns everyone in a small radius.

document.onclick = function(event) {

    if(!player){    //to avoid onclick to be used before calling Player();
        return;
    }

    if(player.canAttack && player.distance >= 80) {     //not for sword attack
        performAttack(player);
        player.canAttack = false;
    }

    if(player.distance < 80)
        performAttack(player);

    //event.preventDefault();
}

document.oncontextmenu = function(event) {

    //hide default behaviour of right click -> no context menu popup
    event.preventDefault();

    if(player.obtainedGadjet > 0) {
        player.pressingMouseRight = true;
        performSpecialAttack(player);
    }

}

In the performAttack function I set player.isStopped = true, so my updatePlayer() doesn't change player.x and player.y while he's attacking. The same for the fireball attack. I want my player stays there.

It works in chrome, my player stops, attacks,and then can moves again, but in Firefox if I right click it somethimes acts instead as I have left clicked, so shoot the magic ball, and maybe then the fireball too. Furthermore, my player ignore isStopped = true, it seems like in Firefox oncontextmenu has "lower priority" than other events.

Any idea? Thanks

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Condo
  • 83
  • 2
  • 10

2 Answers2

0

Please note that a click event contains information about which button was pressed. You can try yourself with something like:

document.addEventListener('click', function(ev){
  console.log(ev.button);
});

And, yes, click events are fired when you right-click, even if you're doing something on related contextmenu events.

So your code should look a bit more like

document.addEventListener('click', function(ev){
  if (ev.button === 0) {
    // Perform primary action
  } else if (ev.button === 2) {
    // Perform secondary action
  }
});

document.addEventListener('contextmenu', function(ev){
  ev.preventDefault();
});
IvanSanchez
  • 18,272
  • 3
  • 30
  • 45
0

Using the same click event is advisable as said by Ivan. You may also want to read this other discussion here on SO about best practices and why it's not always good to disable default right click behaviour (i.e.: it's not always guaranteed to work).

Francesco G.
  • 164
  • 1
  • 6