Detect extended click, javascript

Asked

Viewed 1,261 times

13

Assuming these types of click:

  • 1 CLICK
  • 2 CLICKS IN A ROW
  • EXTENDED CLICK

i know how to detect normal click and dbclick but how to detect extended click? that click you click and secure for X time for example?

  • you can use mousedown but you must have a timeout to confirm. How many milliseconds is "long"?

  • @Sergio would be nice to be adjustable, but in this case it would be something like minimum 2 seconds maximum 4

2 answers

14


Here is a suggestion:

You need a function that runs when there’s a long click. Since this does not exist native you have to create another function that is passed to the event receiver to measure the time. Measure time and stop if there is one mouseup.

I created a function longclick who does just that. Creates some variables that store the state of things in memory and returns a function that, yes, is used by the event receiver.

So when there is a mousedown, the variable mousedown will serve as flag/flag as it turns true. Then fire a counter and if there’s one mouseup flag changes and cancels counter.

I did now at the time, maybe it is possible optimizations, but in general the idea is there.

Edit: I have now added more logic to my function because in case the mousedown and mouseup happen in different elements the click should not be valid. I also added logic for 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: http://jsfiddle.net/n2382xsk/4/

  • 1

    Very good idea, did well what I thought was to create a function "standard". Very good, Thank you, any return doubt. I’ll adapt before I mark it as correct..

  • Sergio, I don’t know if it’s valid by this question but as an associate I’ll ask you. I would like to give the visual feel to the user so that they know they are clicking and holding.. In your example it would have as using the effect scale of the CSS demonstrate this?

  • Taking into account how long he’s holding the div, the smaller the number of the scale (with a logical limit) and when it releases the click the Cale gives a "pulse" (a small zoom, as the elastic gives when repulsed) and back to the original size, could give me ideas of how to do it?

  • @Elaine could do so in its simplest version: http://jsfiddle.net/n2382xsk/5/ To grow you could add a logic with setInterval that increases the scale as time goes on.

  • I liked the way that Plicastes, but I can not put to follow the time, I think it would be a cool effect if every 0.1s he lowered 0.1 in Scale respecting the minimum of 0.4 in total Scale, for div also not disappear.. I would have to call these functions within the setinterval? That’s it?

  • @Elaine if you want to ask a new question about it. I’m on the mobile now and can not help much, but having a setInterval that goes applying style.Transform = 'Scale('+ (size++) +')'; should do what you’re looking for...

  • would it be possible for you to reproduce the Scale effect you made on that fiddle http://jsfiddle.net/n2382xsk/5/ only in its first version? http://jsfiddle.net/n2382xsk/ the one without the maximum count

  • @Elaine, this first fiddle of mine had a possible problem, which is why I improved the answer. But the code without the max and min you want could be like this: http://jsfiddle.net/n2382xsk/7/

Show 3 more comments

4

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

The example below, also taken from the answer to the question "Listen to mouse hold Event on website?", will run an event when the user keeps 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 author of the original reply also made available a example on the Jsfiddle website, in which you can simulate an extended click on the div.

  • I thought it was cool the question but it ends up detecting clicks together, as I explained to @Sergio it should have a minimum and maximum time to be considered an extended click

  • 1

    @Elaine updated the answer considering the minimum and maximum time. So it will be more or less close to what you need?

  • 2

    I liked the way you worked with the parameters, it’s what I want, +1

  • 1

    @Sergio thank you for informing me about these problems. I updated the answer with the appropriate corrections.

Browser other questions tagged

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