Skip to content

Instantly share code, notes, and snippets.

@mattbell87
Last active July 15, 2022 08:19
Show Gist options
  • Save mattbell87/80fe6997ded1feec49a4 to your computer and use it in GitHub Desktop.
Save mattbell87/80fe6997ded1feec49a4 to your computer and use it in GitHub Desktop.
jQuery plugin for Long-press

Longpress plugin for jQuery

This plugin detects a long press on any element for a specified amount of time.

Installation

  • Copy longpress.js to your website
  • Include it in your HTML after you include jQuery.

Usage

To detect if an element has been long-pressed for 2 seconds:

$('.myelement').longpress(function()
{
  alert('I have been long pressed!');
});

To specify the amount of time before it considers it a long press:

$('.myelement').longpress(4000, function() //Replace 4000 with your desired milliseconds
{
  alert('I have been long pressed!');
});
//Long-press Plugin for jQuery
$.fn.longpress = function(time, onlongpress)
{
var timestart = 0;
var timer = null;
//If time wasn't specified
if (!onlongpress)
{
onlongpress = time;
time = 2000; //Default long-press time
}
//When the mouse is down start checking the time
$(this).on( 'mousedown', function( e )
{
timestart = new Date().getTime();
checktime();
});
//Check to see how much time has passed
var checktime = function()
{
if ( new Date().getTime() >= ( timestart + time ) )
{
if (typeof onlongpress == 'function')
{
//Fire the callback
onlongpress();
}
}
else
{
//Keep checking
timer = setTimeout(checktime, 1);
}
}
$(this).on( 'mouseleave mouseup', function( e )
{
//Stop checking if the mouse is up too early or the mouse leaves the element
timestart = 0;
clearTimeout(timer);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment