Doubt about how to call the function with each mouse button

Guys I have this code but I can't get each mouse button to call a different function:

var tela = document.getElementById("tela");
var c = tela.getContext("2d");

c.strokeStyle = "black";
c.strokeRect(0, 0, 600, 400);

var atira = function(evento) {
    var x = evento.pageX - tela.offsetLeft;
    var y = evento.pageY - tela.offsetTop;

    c.fillStyle = "blue";
    c.beginPath();
    c.arc(x, y, 10, 0, 2 * Math.PI);
    c.fill();
};

var atira2 = function(evento) {
    var x = evento.pageX - tela.offsetLeft;
    var y = evento.pageY - tela.offsetTop;

    c.fillStyle = "red";
    c.beginPath();
    c.arc(x, y, 10, 0, 2 * Math.PI);
    c.fill();
};

tela.onclick = function(evento) {
    switch(evento.which) {
        case 1 :
            console.log("botao esquerdo");
            tela.onclick = atira;
            break;
        case 2 :
            console.log("botao do meio");
            tela.onclick = atira2;
            break;
        case 3 :
            console.log("botao direito");
        default:
            console.log("mouse estranho");
    }
}; 
Author: Fernando Leal, 2014-07-30

5 answers

To listen to your buttons, use mousedown.

See:

document.getElementById('workspace').addEventListener('mousedown', function (event) {
  event.preventDefault();

  if(3 === event.which) alert('right click!');
  else alert('left click!');
}, false);

To highlight, workspace is the id element where the user will click and you want to hear the button press.

A complete example, see here, in jsfiddle .


In your specific case, you don't need tela.onclick to engage your functions. See an example I created ( you need remove the comments in question to function ) based on your scenario:

var tela = document.getElementById("tela");

/* 
 * var c = tela.getContext("2d");
 * c.strokeStyle = "black";
 * c.strokeRect(0, 0, 600, 400); 
 */

var atira = function(evento) {
  var x = evento.pageX - tela.offsetLeft;
  var y = evento.pageY - tela.offsetTop;

  c.fillStyle = "blue";
  c.beginPath();
  c.arc(x, y, 10, 0, 2 * Math.PI);
  c.fill();
};

var atira2 = function(evento) {
  var x = evento.pageX - tela.offsetLeft;
  var y = evento.pageY - tela.offsetTop;

  c.fillStyle = "red";
  c.beginPath();
  c.arc(x, y, 10, 0, 2 * Math.PI);
  c.fill();
};

tela.addEventListener('mousedown', function(evento) {
  if(1 === evento.which) {
      console.log('botão esquerdo');
      atira();
  } else if(3 === evento.which) {
      console.log('botão direito'); 
      atira2();
  }
}, false);

tela.addEventListener('contextmenu', function(event) {
  event.preventDefault();
}, false);

The complete example is here, in jsFiddle .


if none of the examples work for you, the problem may be in your DOM. Please post your HTML.

if you don't understand why I'm using .addEventListener, see the documentation here .

 3
Author: Guilherme Oderdenge, 2014-07-30 13:44:23

Your tela.onclick is simply reset itself during the first click, so that every subsequent click will perform the same function every time. Example:

// O mouse foi clicado com o botão esquerdo
tela.onclick = function(evento) {
    switch(evento.which) {
        case 1 :                           // Entrou aqui...
            console.log("botao esquerdo");
            tela.onclick = atira;          // Aqui você redefiniu tela.onclick...
            break;                         // Saiu..
    }
    // ...e não fez mais nada! o primeiro clique não disparou nenhuma função (pun intended).
}; 
// O mouse foi clicado de novo com o botão esquerdo
tela.onclick = atira; // Ele vai executar o código de atira. Parece que funcionou, não? Só que...
// O mouse foi clicado de novo, agora com o botão direito
tela.onclick = atira; // Ele vai executar o código de atira, não de atira3...

Instead of resetting tela.onclick, simply call the relevant function:

tela.onclick = function(evento) {
    switch(evento.which) {
        case 1 :
            console.log("botao esquerdo");
            atira();
            break;
        case 2 :
            console.log("botao do meio");
            atira2();
            break;
        case 3 :
            console.log("botao direito");
            ...
        default:
            console.log("mouse estranho");
    }
}; 

This should solve your immediate problem (of all clicks going to the same function). For a more complete solution, see the answer by William Oderdenge .

 2
Author: mgibsonbr, 2017-04-13 12:59:31

I was also trying to solve this same exercise, and I succeeded as follows:

tela.addEventListener('mousedown', function(evento){

switch(evento.which){

    case 1:
        console.log("botão esquerdo");
        tela.onclick = atira; 
        break;

    case 3:
        console.log("botão direito");
        tela.oncontextmenu = atira2;
        break;

    default:
        console.log("mouse estranho");  

  }
}, false);

The answers posted here helped me in a few points, but what allowed me to "kill the charade" was the understanding that the CLICK event is linked to the Left mouse Button and the CONTEXTMENU event is that it is linked to the right mouse button.

Following material that helped me: events in Javascript

 1
Author: Livia, 2014-11-25 13:54:20

Look, a simple way to perform functions for each mouse click, left and right, is to disable the function responsible for the right click menu and replace it with another, see if it means:

<canvas id = "tela" width = "800" height = "800"> </canvas>

<script>

var tela = document.getElementById("tela");
var c = tela.getContext("2d");

c.fillStyle = "gray";
c.fillRect(0, 0, 800, 800);

var fazCirculoAzul = function(x, y){
    c.fillStyle = "blue";
    c.beginPath();
    c.arc(x, y, 20, 0, 2 * Math.PI);
    c.fill();
}

var fazCirculoVermelho = function(x, y){
    c.fillStyle = "red";
    c.beginPath();
    c.arc(x, y, 20, 0, 2 * Math.PI);
    c.fill();
}

tela.onclick = function(evento){

    var x = evento.pageX - tela.offsetLeft;
    var y = evento.pageY - tela.offsetTop;

    fazCirculoAzul(x, y);
}

tela.oncontextmenu = function(evento){
    evento.preventDefault();
    var x = evento.pageX - tela.offsetLeft;
    var y = evento.pageY - tela.offsetTop;

    fazCirculoVermelho(x, y);
}

</script>
 1
Author: Lucas Silva, 2016-04-03 23:50:45

Browsers understand that onclick is only for left-button clicks! Note that when you right-click, a small window with the actions menu opens. The function that takes care of this is that of the oncontextmenu and, to prevent the browser from opening the menu window, you can still add the event call.preventDefault ():

<canvas id="tela" width="600" height="400"></canvas>

<script>
	var tela = document.getElementById("tela");
	var c = tela.getContext("2d");

	c.fillStyle="gray";
	c.fillRect(0, 0, 600, 400);


	var atiraVermelho = function(evento) {
		var x = evento.pageX - tela.offsetLeft;
		var y = evento.pageY - tela.offsetTop;

		c.fillStyle="red";
		c.beginPath();
		c.arc(x, y, 5, 0, 2*3.14);
		c.fill();
	};

	var atiraAzul = function(evento) {
		var x = evento.pageX - tela.offsetLeft;
		var y = evento.pageY - tela.offsetTop;

		c.fillStyle="blue";
		c.beginPath();
		c.arc(x, y, 5, 0, 2*3.14);
		c.fill();

		evento.preventDefault();
	};

	tela.onclick = atiraVermelho;
	tela.oncontextmenu = atiraAzul;

</script>
 0
Author: Allan Barbosa, 2016-07-28 22:42:35