How can I listen for a click-and-hold in jQuery?
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
jQuery Listen Only When Click Hold
You'd store something in mousedown
and mouseup
that you can access in mousemove
$(document).on({ mousedown: function(e) { e.preventDefault();
if (e.which === 2) $(window).data('isDown', true).data('mPosX', e.pageX).data('mPosY', e.pageY); }, mouseup: function(e) { e.preventDefault();
if (e.which === 2) $(window).data('isDown', false); }, mousemove: function(e) { if ($(window).data('isDown')) { var CmPosX = e.pageX, CmPosY = e.pageY, mPosX = $(window).data('mPosX'), mPosY = $(window).data('mPosY');
console.log('Original X: ' + mPosX + ', New X: ' + CmPosX + ' | Original Y: ' + mPosY + ', New Y: ' + CmPosY); } }});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><p>Hold down mousewheel and move ...</p>
Click and Hold event listener with Javascript
You can use Javascript's setTimeout
function and bind it to mousedown
events. Have a look at the snippet below:
// click and hold event listener
var timeout_id = 0, hold_time = 1000, hold_menu = $('.hold_menu'), hold_trigger = $('.hold_trigger');
hold_menu.hide();
hold_trigger.mousedown(function() { timeout_id = setTimeout(menu_toggle, hold_time);}).bind('mouseup mouseleave', function() { clearTimeout(timeout_id);});
function menu_toggle() { hold_menu.toggle();}
ul.hold_menu { list-style: none; padding: 0; margin: 0;}
ul.hold_menu a, div.hold_trigger { display: inline-block; padding: 5px 15px; border: 1px solid #ccc; width: 300px;}
ul.hold_menu a:link, ul.hold_menu a:visited { color: black; text-decoration: none;}
ul.hold_menu a:active, ul.hold_menu a:hover { background: #ff0; text-decoration: none;}
div.hold_trigger { color: black; cursor: pointer;}
div.hold_trigger:hover { background: #ccc;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hold_trigger">Click and hold to toggle the menu</div><ul class="hold_menu"> <li><a href="#">Option 1</a></li> <li><a href="#">Option 2</a></li> <li><a href="#">Option 3</a></li></ul>
Return false; When mouse hold(click) in x seconds
You need to add a click
handler and, if your func
was called, prevent the default action of the click. Here I'm using timer
as a flag:
var timer = 0;
var func = function () {
$("body").append("1");
timer = 0;
};
$(document).on('mousedown' , 'a' , function(e){
timer = setTimeout(func, 1000);
}).on('mouseup mouseleave' , 'a' , function(e){
if (timer) {
clearTimeout(timer);
}
}).on('click', 'a', function() {
if (!timer) {
return false;
}
});
Updated JSBin
listen to mouse hold event on website?
If you want the hold state then it will be the state when you are in mousedown event state for a while. This state exists when you press mousedown but not mouseup. Hence you need to take a variable which records the current state of the event.
JS
$('div').on('mousedown mouseup', function mouseState(e) {
if (e.type == "mousedown") {
//code triggers on hold
console.log("hold");
}
});
Working Fiddle
How to detect a long press on a div in Jquery?
Just watch both mousedown
and mouseup
and calculate the difference. Here's an example.
(function() {
// how many milliseconds is a long press?
var longpress = 3000;
// holds the start time
var start;
jQuery( "#pressme" ).on( 'mousedown', function( e ) {
start = new Date().getTime();
} );
jQuery( "#pressme" ).on( 'mouseleave', function( e ) {
start = 0;
} );
jQuery( "#pressme" ).on( 'mouseup', function( e ) {
if ( new Date().getTime() >= ( start + longpress ) ) {
alert('long press!');
} else {
alert('short press!');
}
} );
}());
How can I detect a click and hold in Coffeescript and then return instead of running what's next?
I managed to get it working.
I needed to change the function to use $(document).on 'mousedown'. Ultimately it ended up looking like this, with a little extra code to handle the checkbox being checked or unchecked:
# We'll manage checking the checkbox thank you very much
$(document).on 'click', '.task > label', (e) ->
e.preventDefault()
# Clicking on the checkbox or label to mark a task as completed
$(document).on 'mousedown', '.task > label', ->
holding = false
# If they haven't released the mouse after 250 milliseconds,
# then they're probably dragging and we don't want to (un)check
setTimeout (->
holding = true
), 250
$(this).one 'mouseup', ->
checkbox = undefined
unless holding
# They're not dragging, check the checkbox
checkbox = $('input', this)
checkbox.prop 'checked', not checkbox.prop('checked')
# Get the task li
li = $(this).closest('li')
# Slide it up and hide it
# Use Views.getId(li) to get the task id
# Then pass it to Task.markDone() to get checked off
li.slideToggle ->
Task.markDone(Views.getId(li))
How can I listen for a click-and-hold in AngularJS?
DEMO
<span class="time">{{ Time | timeFilter }}</span>
<div class="btn-group btn-group-sm">
<button class="btn btn-default" ng-mousedown='mouseDown()' ng-mouseup="mouseUp()">
<i class="fa fa-caret-up"></i>
</button>
<button class="btn btn-default" ng-click="Time = Time - 1">
<i class="fa fa-caret-down"></i>
</button>
</div>
Use ng-mouseDown and ng-mouseup directive with $interval
app.directive('time', function ($interval) {
return {
templateUrl: 'time.html',
restrict: 'E',
scope: {
Time: '=value'
},
link: function (scope, element, attrs) {
element.addClass('time');
var promise;
scope.mouseDown = function() {
if(promise){
$interval.cancel(promise);
}
promise = $interval(function () {
scope.Time++;
}, 100);
};
scope.mouseUp = function () {
$interval.cancel(promise);
promise = null;
};
}
};
});
Related Topics
JavaScript Getelementbyid Based on a Partial String
Converting JSON Results to a Date
Google Bar Chart Cannot Change Individual Bar Color
Getting a Unhandledpromiserejectionwarning When Testing Using Mocha/Chai
Auto-Refreshing Div with Jquery - Settimeout or Another Method
JavaScript Return Number of Days,Hours,Minutes,Seconds Between Two Dates
[Vue Warn]: Property or Method Is Not Defined on the Instance But Referenced During Render
Does a JavaScript If Statement with Multiple Conditions Test All of Them
Checking If Image Does Exists Using JavaScript
Get Character Value from Keycode in JavaScript... Then Trim
Unsafe JavaScript Attempt to Access Frame with Url
Downloading Canvas Element to an Image
Convert Simple Array into Two-Dimensional Array (Matrix)
Should I Refrain from Handling Promise Rejection Asynchronously
Why Are Objects Not Iterable in JavaScript
How to Store a Global Value (Not Necessarily a Global Variable) in Jquery
JavaScript Ie Detection, Why Not Use Simple Conditional Comments