4

I'm trying to find a way to execute a button function only if the user pressed/clicked on the button for 10 seconds.

the normal button function is:

$( "#target" ).click(function() {
alert( "Handler for .click() called." );
});

so is there any way to count the seconds from the moment the user pressed on the button and KEPT pressing, (a continuous pressing without clicking not tapping), and when the seconds hits 10, the function will execute?

Huangism
  • 16,278
  • 7
  • 48
  • 74
user3806613
  • 510
  • 2
  • 11
  • 25

5 Answers5

6

You'll need timers, set one when the mouse is held down, clear it when the mouse is released.

$( "#target" ).on({
    mousedown: function() {
        $(this).data('timer', setTimeout(function() {
              foo();
        }, 10000));
    },
    mouseup: function() {
        clearTimeout( $(this).data('timer') );
    }
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

You have to use mousedown and mouse up instead of click event ,

var timeOut = 0;
$("#target").mousedown(function () {
    clearTimeout(timeOut);
    timeOut = setTimeout(function () {
        console.log("Handler for .click() called.");
    }, 10000);
});
$(document).mouseup(function () {
    clearTimeout(timeOut);
    console.log("stop");
})

DEMO

Balachandran
  • 9,567
  • 1
  • 16
  • 26
0

The jQuery LongPress plugin will handle this for you.

https://github.com/vaidik/jquery-longpress

You can set the delay parameter before your function executes.

Len_D
  • 1,422
  • 1
  • 12
  • 21
0

JS

var threshold = 10000, timeOne, timeTwo;
$('#t10').mousedown(function(){
    timeOne = new Date();
}).mouseup(function(){
    timeTwo = new Date();
    if(timeTwo - timeOne >= threshold){
        alert('Do what you want');
        timeOne = 0;
    }else{
        console.log('Released early');
    }
});

HTMl

<button  id="t10">XX</button>

Fiddle http://jsfiddle.net/5z94y2z5/

A dev
  • 930
  • 3
  • 12
  • 27
0

you needs to use mousedown and mouseup events

http://api.jquery.com/mousedown/ http://api.jquery.com/mouseup/

var pressedtensecondos = false;
var timer = null;

$( "#target" ).mousedown(function() {
  timer = setTimeout(function() { pressedtensecondos = true; }, 10000);
});

$( "#target" ).mouseup(function() {
  clearTimeout(timer);
  
  if(pressedtensecondos)
    alert('ten seconds');

  pressedtensecondos = false;
});
lem2802
  • 1,152
  • 7
  • 18