Action while the button is being clicked

1

Is it possible to know if the left mouse button is clicked using Javascript?

It is not whether it has been clicked, but whether it has been pressed and still continues. When I click it it changes a value and after dropping it back the value, I'll have to move it clicked too. I do not know if I was clear, but I think you can understand.

I do not have code, because it's something I need to implement, but if that's all I've described is possible it might be useful.

    
asked by anonymous 05.07.2018 / 19:10

2 answers

2

Unfortunately, JavaScript does not have a method that detects the click continuously. The mousedown event is triggered when you click either the left or the right button and it is only detected once, even if you hold the click.

The event mouseup does the inverse, detects when the click is released.

What you can do to simulate a continuous action with mousedown is to insert a setInterval by calling an action repeatedly after a short interval. When you release the click, trigger the mouseup event by canceling the setInterval .

Now since mousedown detects both left and right click, you can use the buttons property of the event to know which button was clicked:

buttons: 1 (clique esquerdo)
buttons: 2 (clique direito)

You can also disable the menu that opens to the right click. To do this, return false in event contextmenu :

botao.addEventListener("contextmenu", function(e){
   e.preventDefault();
}, false);

Example:

var botao = document.getElementById("botao");
var intervalo;
botao.addEventListener("mousedown", function(e){
   if(e.buttons == 2){
      intervalo = setInterval(pressionado, 100);
   }
});

botao.addEventListener("mouseup", function(){
   clearInterval(intervalo);
});

// desativar o menu do clique direito
botao.addEventListener("contextmenu", function(e){
   e.preventDefault();
}, false);

function pressionado(){
   var html = '<p>texto</p>';
   document.getElementById("areadeteste").innerHTML += html;
}
<button id="botao">Clique aqui com o botão direito, segure um pouco e solte</button>
<div id="areadeteste"></div>
    
05.07.2018 / 21:15
1

Hello.

So you said, you need an event that understands that the user clicked an element but did not release the "click" button, right?

You can use the onmousedown event. When the user clicks the left button, this event will occur, and as long as the next event - "onmouseup" - does not occur, it means that the button is still pressed. Got it?

The following simple example (click and hold remains in the same event): link

You're thinking like it's three events, but actually they're only two.

Good luck.

    
05.07.2018 / 21:02