Question on how to call the function with each mouse button

Asked

Viewed 4,870 times

4

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");
    }
}; 
  • Can also put your html? can be only the relevant part.

5 answers

3

To listen to your buttons, use mousedown.

Behold:

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

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

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

A complete example, see here, in jsFiddle.


In your specific case, you don’t need the tela.onclick to trigger your functions. See an example I created (you need remove the comments in question to work) 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 can be on your DOM. Please post your HTML.

If you don’t understand why I’m using .addEventListener, see the documentation here.

  • 2

    Yoda conditions!

  • I can’t not use it, @Beet. Uahua

  • The author of the question reported to have tried this and obtained the following error: Uncaught Typeerror: Cannot read Property 'pageX' of Undefined. (I deleted his posting because it was posted as a response).

  • 2

    Hi @bfavaretto. So he gave CTRL+C / CTRL+V in my code and this reaction is more than normal - is expected. As you can see in the code and even in the warning of my post, there are three lines that I commented in his code so that I could better exemplify - lines that if absent result in such error by the user presented. Therefore, it is up to him to uncomment the lines and make the amendments I proposed in my (s) example(s)).

2

Your tela.onclick is simply reset to 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 redefining the 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 reply from Guilherme Oderdenge.

1

I was also trying to solve this same exercise, and I got it this way:

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 some points, but what allowed me to "kill the puzzle" was the understanding that the CLICK event is linked to the left mouse button and the CONTEXTMENU event is linked to the right mouse button.

Follow material that helped me: javascript events

1

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 with another, see if understand:

<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>

0

Browsers understand that onclick is for left-click only! Note that when you right-click, a window with the action menu opens. The function that takes care of this is the oncontextmenu and, to prevent the browser from opening the menu window, you can still add the call to the event.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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.