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

JavascriptJqueryEvents

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

I made a simple JQuery plugin for this if anyone is interested.

http://plugins.jquery.com/pressAndHold/

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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

Solution 8 - Javascript

Try this:

var thumbnailHold;

	$(".image_thumb").mousedown(function() {
		thumbnailHold = setTimeout(function(){
			 checkboxOn(); // Your action Here
			 
		 } , 1000);
	 return false;
});

$(".image_thumb").mouseup(function() {
	clearTimeout(thumbnailHold);
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSnickersAreMyFaveView Question on Stackoverflow
Solution 1 - JavascripttreefaceView Answer on Stackoverflow
Solution 2 - JavascriptgnarfView Answer on Stackoverflow
Solution 3 - JavascriptTony SmithView Answer on Stackoverflow
Solution 4 - JavascriptJacob MattisonView Answer on Stackoverflow
Solution 5 - Javascriptkayz1View Answer on Stackoverflow
Solution 6 - JavascriptSnickersAreMyFaveView Answer on Stackoverflow
Solution 7 - JavascriptSergey SemushinView Answer on Stackoverflow
Solution 8 - JavascriptKR VineethView Answer on Stackoverflow