Button function if the button is pressed for 10 seconds? [duplicate] - javascript

This question already has answers here:
How can I listen for a click-and-hold in jQuery?
(8 answers)
Closed 8 years ago.
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?

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

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

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.

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/

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

Related

Prototype.js how to fix use of clearTimeout( )

I'm using Prototype.js to load an html element when the user performs a mouseover on certain list items. I'm using setTimeout() to load the content only if the mouse is still over the list item after a given amount of time. I want to use clearTimeout when the user performs a mouseout on the same list item.
clearTimeout() is not clearing my timeout. I am pretty sure this is because of a common variable scope issue hidden from me by my lack of familiarity with Prototype.js
Can someone point out the flaw in this code or determine what I need to add to make the clearTimeout() function work properly?
document.observe( 'dom:loaded', function() {
var timeout;
$$('.nav-primary li.category').each( function( item ) {
item.observe('mouseover', function(event) {
event.stopPropagation();
categoryId = event.currentTarget.id;
getCategoryBlurb(categoryId);
timeout = setTimeout( function() {
showCategoryInfo(categoryData, categoryId);
}, waitTime);
});
item.observe('mouseout', function(event) {
event.stopPropagation();
clearTimeout(timeout);
});
});
});
Updated Code
$$('.nav-primary li.category').each( function( item ) {
var timeout = null;
item.observe('mouseover', function(event) {
event.stopPropagation();
categoryId = event.currentTarget.id;
getCategoryBlurb(categoryId);
if( timeout === null ) {
timeout = setTimeout( function() {
showCategoryInfo(categoryData, categoryId);
}, waitTime);
}
console.log(timeout);
});
item.observe('mouseout', function(event) {
if( timeout !== null ) {
console.log(timeout);
clearTimeout(timeout);
timeout = null;
}
});
});
clear the timeout before you set it
if (timeout) { clearTimeout(timeout); }
timeout = setTimeout( function() { /* code here */ });

How to cancel timeout if user performs click

I want to display a pop-up window after 10 second if any other click event is not performed. i.e. I displayed the pop-up window after 10 as:
setTimeout( "jQuery('#rollup-page-Modal').modal('show');",10000 );
Now there are few pop-up windows which will be displayed once clicked as:
jQuery(".more-info").click(function(event){
jQuery("#more-info-modal").modal('show');
event.preventDefault();
});
jQuery(".call-now").click(function(event){
jQuery("#request-callback-modal").modal('show');
event.preventDefault();
});
jQuery(".popup-send-quote").click(function(){
jQuery("#request-callback-modal").modal('hide');
jQuery("#callback-thankyou-modal").modal('show');
});
Now I want, the first pop-up window (which will be displayed after 10 sec) should not be displayed if any other pop-up windows is displayed or any other click event is performed.
You should to store the id of the timeout in a variable, then you can use window.clearTimeout() to clear the timeout when a click happens in the document:
var timer = setTimeout( "jQuery('#rollup-page-Modal').modal('show');",10000 );
$(document).on("click",function(){
clearTimeout(timer);
});
Add a flag
var didClick = false;
jQuery(".more-info").click(function(event){
jQuery("#more-info-modal").modal('show');
event.preventDefault();
didClick = true;
});
jQuery(".call-now").click(function(event){
jQuery("#request-callback-modal").modal('show');
event.preventDefault();
didClick = true;
});
jQuery(".popup-send-quote").click(function(){
jQuery("#request-callback-modal").modal('hide');
jQuery("#callback-thankyou-modal").modal('show');
didClick = true;
});
then set it to false before timeout
didClick = false;
setTimeout(function() {
if (!didClick) {
jQuery('#rollup-page-Modal').modal('show');
}
},10000 );
first the timeout code:
var timeout = setTimeout( function () {
jQuery('#rollup-page-Modal').modal('show');
},10000 );
now that it's in a var you can cancel it elsewhere in the code:
jQuery(".more-info").click(function(event){
clearTimeout(timeout);
jQuery("#more-info-modal").modal('show');
event.preventDefault();
});
jQuery(".call-now").click(function(event){
clearTimeout(timeout);
jQuery("#request-callback-modal").modal('show');
event.preventDefault();
});
jQuery(".popup-send-quote").click(function(){
clearTimeout(timeout);
jQuery("#request-callback-modal").modal('hide');
jQuery("#callback-thankyou-modal").modal('show');
});

delay mouseenter event and raise event if mouse inside the element

I use this tab view that developed base on jQuery:
https://d2o0t5hpnwv4c1.cloudfront.net/001_Tabbed/site/jQuery.html#
I change the code that tabs change by mouseenter event. and I want to delay execution of the mouseenter event so if mouse enter the elemnt and remain there for portion of time mouseenter executes else (if mouse go outside in time less that that portion of time) mouseenter does not execute.I write this code:
$(document).ready(function () {
$('a.tab').on('mouseenter', function () {
var thisElement = $(this);
setTimeout(function () {
$(".active").removeClass("active");
thisElement.addClass("active");
$(".content").slideUp();
var content_show = thisElement.attr("title");
$("#" + content_show).slideDown();
}, 300);
});
});
but if I bring mouse out of element mouseenter excecutes.How to solve this problem?
thanks
You need to store the timeout handle and cancel it on mouseleave:
var timeout;
$(document).ready(function () {
$('a.tab').on('mouseenter', function () {
var thisElement = $(this);
if (timeout != null) { clearTimeout(timeout); }
timeout = setTimeout(function () {
$(".active").removeClass("active");
thisElement.addClass("active");
$(".content").slideUp();
var content_show = thisElement.attr("title");
$("#" + content_show).slideDown();
}, 300);
});
$('a.tab').on('mouseleave', function () {
if (timeout != null) {
clearTimeout(timeout);
timeout = null;
}
});
});

On keypress, when stop after X seconds call function

I have a text input and a textarea and I'm passing the value from the input to the textarea. I am trying to do, when you type something in the input and you stop, after 2 seconds show the values to the textarea.
In this example the textarea gets the input's value instantly:
http://jsfiddle.net/DXMG6/
So i want, when you type and stop, after 2 seconds give the value.
How can I achieve this? I tried to use setTimeout but when the 2 seconds pass, then it keeps getting the value instantly. So basically it works for the first 2 seconds.
You have to reset the timer everytime the user presses the key again:
jQuery(function($){
function changeFn(){
alert('Changed');
}
var timer;
$("#string").bind("keyup", function(){
clearTimeout(timer);
timer = setTimeout(changeFn, 2000)
});
});
Once i made this plugin called bindDelay for jQuery:
$.fn.bindDelay = function( eventType, eventData, handler, timer ) {
if ( $.isFunction(eventData) ) {
timer = handler;
handler = eventData;
}
timer = (typeof timer === "number") ? timer : 300;
var timeouts;
$(this).bind(eventType, function(event) {
var that = this;
clearTimeout(timeouts);
timeouts = setTimeout(function() {
handler.call(that, event);
}, timer);
});
};
Used like a normal bind method but the last argument is the delay before firing the handler (in mil sec):
$("input").bindDelay('keyup', function() {
$("textarea").text( $(this).val() );
}, 2000);
See fiddle: http://jsfiddle.net/c82Ye/2/
And you unbind and trigger it like normal:
$("input").unbind("keyup");
$("input").trigger("keyup");
setTimeout returns an ID of the "job". what you have to do is to clearTimeout(id) every type and setTimeout again:
var tID = null;
onclick() {
if (tID !== null) clearTimeout(tID);
tID = setTimeout(function() { /*Do domething*/ }, 2000);
}
What you need to do is set a timeout, and save the resulting timeout id. Then you need to check if the timeout id has been saved at each keypress. If the timeout is set, clear the timeout and reset it. Something like this:
var timeoutId = null;
var myFunc = function() {
timeoutId = null;
// Do stuff
};
var myEventHandler = function() {
if (timeoutId) {
window.clearTimeout(timeoutId);
}
timeoutId = window.setTimeout(myFunc, 2000);
};
...or check the updated fiddle:
http://jsfiddle.net/DXMG6/5/
I've updated your fiddle
This will update the textarea value 2 seconds after you end editing the text.
The relevant part is this: we keep a reference to a timeout, when the keyup event is fired we clear the previous timeout and we start a new timeout, that will fire in 2 seconds.
var timeout = null;
$("#string").on("keyup keypress paste mouseup", function () {
clearTimeout(timeout);
timeout = setTimeout(function() {
// ... your code here
}, 2000);
});
Try something like this. Use setTimeout, but each time a key is pressed, reset the timer and start over...
http://jsfiddle.net/DXMG6/10/
var textTimer=null;
$("#string").on("keyup keypress paste mouseup", function () {
if (textTimer) clearTimeout(textTimer);
textTimer = setTimeout(function(){
var a = $('#string').val();
$('#rdonly').html(a);
}, 2000);
});
$('.btn').click(function() {
$('#rdonly').text('');
$('#string').val('');
});
You just need to modify your code as follows:
var timeoutId = 0;
$("#string").on("keyup keypress paste mouseup", function () {
var a = $('#string').val();
// Cancel existing timeout, if applicable
if (timeoutId > 0) {
window.clearTimeout(timeoutId);
}
// Start a timeout for 2 seconds- this will be cancelled above
// if user continues typing
timeoutId = window.setTimeout(function () {
$('#rdonly').html(a);
}, 2000);
});

How can I listen for a click-and-hold in jQuery?

I want to be able to fire an event when a user clicks on a button, then holds that click down for 1000 to 1500 ms.
Is there jQuery core functionality or a plugin that already enables this?
Should I roll my own? Where should I start?
var timeoutId = 0;
$('#myElement').on('mousedown', function() {
timeoutId = setTimeout(myFunction, 1000);
}).on('mouseup mouseleave', function() {
clearTimeout(timeoutId);
});
Edit: correction per AndyE...thanks!
Edit 2: using bind now for two events with same handler per gnarf
Aircoded (but tested on this fiddle)
(function($) {
function startTrigger(e) {
var $elem = $(this);
$elem.data('mouseheld_timeout', setTimeout(function() {
$elem.trigger('mouseheld');
}, e.data));
}
function stopTrigger() {
var $elem = $(this);
clearTimeout($elem.data('mouseheld_timeout'));
}
var mouseheld = $.event.special.mouseheld = {
setup: function(data) {
// the first binding of a mouseheld event on an element will trigger this
// lets bind our event handlers
var $this = $(this);
$this.bind('mousedown', +data || mouseheld.time, startTrigger);
$this.bind('mouseleave mouseup', stopTrigger);
},
teardown: function() {
var $this = $(this);
$this.unbind('mousedown', startTrigger);
$this.unbind('mouseleave mouseup', stopTrigger);
},
time: 750 // default to 750ms
};
})(jQuery);
// usage
$("div").bind('mouseheld', function(e) {
console.log('Held', e);
})
I made a simple JQuery plugin for this if anyone is interested.
http://plugins.jquery.com/pressAndHold/
Presumably you could kick off a setTimeout call in mousedown, and then cancel it in mouseup (if mouseup happens before your timeout completes).
However, looks like there is a plugin: longclick.
var _timeoutId = 0;
var _startHoldEvent = function(e) {
_timeoutId = setInterval(function() {
myFunction.call(e.target);
}, 1000);
};
var _stopHoldEvent = function() {
clearInterval(_timeoutId );
};
$('#myElement').on('mousedown', _startHoldEvent).on('mouseup mouseleave', _stopHoldEvent);
Here's my current implementation:
$.liveClickHold = function(selector, fn) {
$(selector).live("mousedown", function(evt) {
var $this = $(this).data("mousedown", true);
setTimeout(function() {
if ($this.data("mousedown") === true) {
fn(evt);
}
}, 500);
});
$(selector).live("mouseup", function(evt) {
$(this).data("mousedown", false);
});
}
I wrote some code to make it easy
//Add custom event listener
$(':root').on('mousedown', '*', function() {
var el = $(this),
events = $._data(this, 'events');
if (events && events.clickHold) {
el.data(
'clickHoldTimer',
setTimeout(
function() {
el.trigger('clickHold')
},
el.data('clickHoldTimeout')
)
);
}
}).on('mouseup mouseleave mousemove', '*', function() {
clearTimeout($(this).data('clickHoldTimer'));
});
//Attach it to the element
$('#HoldListener').data('clickHoldTimeout', 2000); //Time to hold
$('#HoldListener').on('clickHold', function() {
console.log('Worked!');
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<img src="http://lorempixel.com/400/200/" id="HoldListener">
See on JSFiddle
Now you need just to set the time of holding and add clickHold event on your element
Try this:
var thumbnailHold;
$(".image_thumb").mousedown(function() {
thumbnailHold = setTimeout(function(){
checkboxOn(); // Your action Here
} , 1000);
return false;
});
$(".image_thumb").mouseup(function() {
clearTimeout(thumbnailHold);
});

Categories

Resources