Detect prolonged click, javascript

13

Assuming these types of clicks:

  • 1 CLICK
  • 2 CLIQUES FOLLOWED
  • PROLONGED CLICK

I know how to detect the normal click and dbclick but how to detect the extended click? that click that you click and hold for X time for example?

    
asked by anonymous 11.07.2015 / 16:59

2 answers

14

Here's a suggestion:

You need a function that runs when there is a long click. Since there is no native you have to create another function that is passed to the event observer to measure the time. Measure time and stop if there is a mouseup .

I created a longclick function that does this. It creates some variables that store the state of things in memory and returns a function that is used by the event observer.

In this way, when there is a mousedown, the variable mousedown will serve as flag / flag because it will true . There it fires a counter and if there is a mouseup the flag changes and cancels the counter.

I've done it now, maybe optimizations are possible, but the idea is generally there.

Edit: I have now added more logic in my function because if the mousedown and the mouseup happen in different elements the click must not be valid. I also added logic to maximum and minimum.

var longclick = function (cb) {
    var min = 2000;
    var max = 4000;
    var time, self, timeout, event;

    function reset() {
        clearTimeout(timeout);
        timeout = null;
    }

    window.addEventListener('mouseup', reset); // caso o mouseup ocorra fora do elemento
    return function (e) {
        if (!self) {
            self = this;
            self.addEventListener('mouseup', function (e) {
                e.stopPropagation(); // para não subir no DOM
                var interval = new Date().getTime() - time;
                if (timeout && interval > min) cb.call(self, event);
                reset();
            });
        }
        event = e;
        time = new Date().getTime();

        if (e.type == 'mousedown') timeout = setTimeout(reset, max);
    };
};

var div = document.querySelector('div');
var handler = longclick(function (e) {
    alert('clicado entre 2 e 4 segundos! ' + e.type);
    this.style.backgroundColor = '#ccf';
});
div.addEventListener('mousedown', handler);

jsFiddle: link

    
11.07.2015 / 17:39
4

According to the answer to this question in English "Listen to mouse hold event on website?" , you need pass a parameter to the mousedown and mouseup events so that you can identify if the event type is mousedown , thus indicating that the user is holding down the left mouse button.

The example below, also extracted from the answer to the "Listen to mouse hold event on website?" an event when the user maintains an extended click on any div:

<div data-tempoMinimo="2000" data-tempo-maximo="4000" data-tempo-decorrido="0"></div>

$('div').on('mousedown mouseup', function mouseState(e) {
    var div = $('div');

    if (div.data('tempo-decorrido') == 0) {
        var horaAtual = new Date();

        // Devido ao JavaScript ser muito rápido, julguei necessário
        // diminuir um milisegundo da hora atual para evitar que o código
        // após esse if sempre retorne zero em newDate() - div.data('momento-ultimo-click').
        horaAtual.setMilliseconds(horaAtual.getMilliseconds() - 1);

        div.data('momento-ultimo-click', horaAtual);   
    }

    // Obtém o tempo decorrido em milisegundos.
    var tempoDecorrido = new Date() - div.data('momento-ultimo-click');

    // Verifica se já se passou o tempo mínimo
    if (tempoDecorrido > div.data('tempo-minimo') && e.type == "mousedown") {
        // Código executado ao manter o clique prolongado.
        console.log("Evento clique prolongado executado.");            
    }

    // Reseta o momento do último clique para que o tempo mínimo seja considerado novamente antes de atirar o evento.
    if (tempoDecorrido > div.data('tempo-maximo')) {
        div.data('momento-ultimo-click', new Date());
    }
});

The original response author has also made a example on the JSFiddle site , where you can simulate an extended click event in the div.

    
11.07.2015 / 17:26