Search code examples
javascriptjqueryioscssmobile-safari

recognize long tap without mouseup


I try to recognize a long tap to start a shake animation but I want to start it while the button is pressed not after I get the mouseup event. Till now I have the following code which performs exactly what I don't want but it's a beginning..

var offset = 10;
$('body').on('mousedown','.img-select', function (e) {
    $(this).data('start', new Date().getTime());
}).on('mouseup','.img-select', function (e) {
    if (new Date().getTime() >= ($(this).data('start') + offset)) {
        this.blur(); //to avoid a selectbox from opening
        window.focus(); //to avoid a selectbox from opening
        $('.img-item').addClass('shake');
    }
}).on('mouseleave','.img-select', function (e) {
    start = 0;
});

From @prajmus suggested Idea:

$('body').on('mousedown','.img-select', function (e) {
    //$(this).data('start', new Date().getTime());
    setTimeout(function(){
      $('.img-item').addClass('shake');
    },1000);
}).on('mouseup','.img-select', function (e) {
    /*if (new Date().getTime() >= ($(this).data('start') + offset)) {
        this.blur();
        window.focus();
        $('.img-item').addClass('shake');
    }else{

    }*/
}).on('mouseleave','.img-select', function (e) {
    start = 0;
});

It appears that the code inside my mousedown event handler first launched when I released the button ?!

And for some reason the code inside my timeout recommended from @prajmus wasn't executed at all.

In my imagination it should like you hold an app icon in ios..


Solution

  • You have to assign the timer to a variable:

    var timeout;
    $('body').on('mousedown','.img-select', function (e) {
        timeout = setTimeout(function(){
          $('.img-item').addClass('shake');
        },1000);
    }).on('mouseup','.img-select', function (e) {
        clearTimeout(timeout);
    }).on('mouseleave','.img-select', function (e) {
        start = 0;
    });
    

    Check out jsfiddle