Button function if the button is pressed for 10 seconds?

I am trying to find a way to execute a button function only if the user has pressed / pressed the button for 10 seconds.

normal button function:

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

      

so is there a way to count the seconds from the moment the button is pressed by pressing the button and pressing KEPT (continuous press without pressing for not pressing), and when the seconds reach 10, the function will execute?

+3


source to share


5 answers


You will need timers, set them when the mouse is held down, clear it when the mouse is released.

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

      



FIDDLE

+5


source


You should 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

0


source


The jQuery LongPress plugin will handle this for you.

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

      

You can set the delay parameter before executing your function.

0


source


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>

      

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

0


source


you need 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;
});
      

Run code


0


source







All Articles