I needed an event for a “long press” with the mouse, or a “long touch” event on the mobile devices. This one does the following:
- depends on jQuery
- prevents the “click” event from firing, in case the “longpress” event occurs
- “longpress” does not fire if the mouse leaves the element during pressing
- the following examples attaches to all elements specified by the selector
(function( selector ){
var $ = ( typeof jQuery !== 'undefined' ) ? jQuery : false;
if( !$ ) return;
var isLongClick = false,
isMouseIn = false,
pressTimer,
pressDelay = 1000; // ms
$(selector)
.on( 'mousedown touchstart', function(e){
var $this = $(this);
pressTimer = window.setTimeout(function() {
if( typeof e.button !== 'undefined' && e.button !== 0 ) return; // prevent trigger on right-click
if( isMouseIn ){
isLongClick = true;
$this.trigger( 'longpress' );
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
}
}, pressDelay);
} )
.on( 'mouseup touchend', function(e){
clearTimeout(pressTimer);
} )
.on( 'click', function(e){
if( isLongClick ){
isLongClick = false; // reset this flag (it has done its part)
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}
} )
.on( 'mouseover touchstart', function(e){
isMouseIn = true;
} )
.on( 'mouseout touchleave touchcancel', function(e){
isMouseIn = false;
} )
;
})( '.btn' );