Peter
Peter

Reputation: 1931

How to fix multiple execution when using jquery onclick and mouseup event to detect long press

I have a function which opens bootstrap modal when click on div element, everything is working fine on my computer, but some time on mobile when i click on the div it will show css focus around the element without executing the function in onclick method till i click on it the second time. So i tried using the below code to detect any click on the element except long pressing which i thing it will help. All works fine when i click once the function execute but always execute multiple time and it has ajax request inside which also send multiple time.

var longpress = 3000;
var start;
	
$(document).on( 'mousedown focusIn',  '.openIt', function( event ) {
	start = new Date().getTime();
});

$(document).on( 'mouseleave focusOut', '.openIt', function( event ) {
	start = 0;
});
	
 $(document).on("click mouseup", '.openIt', function(event){
	if ( new Date().getTime() >= ( start + longpress )  ) {
		console.log(event.type, " is long press!");
	} else {
	    //$.myfynctionHere({.......});
		console.log(event.type, " is short press!");
	}
	event.preventDefault();
});
.openIt{
  color: #fff;
  background-color: #000;
  height: 30px;
  width: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="openIt">Open Item</div>

Upvotes: 1

Views: 176

Answers (1)

semanser
semanser

Reputation: 2348

Just remove mouseup event from the event handler

var longpress = 3000;
var start;
	
$(document).on( 'mousedown focusIn',  '.openIt', function( event ) {
	start = new Date().getTime();
});

$(document).on( 'mouseleave focusOut', '.openIt', function( event ) {
	start = 0;
});
	
 $(document).on("click", '.openIt', function(event){
	if ( new Date().getTime() >= ( start + longpress )  ) {
		console.log(event.type, " is long press!");
	} else {
	    //$.myfynctionHere({.......});
		console.log(event.type, " is short press!");
	}
	event.preventDefault();
});
.openIt{
  color: #fff;
  background-color: #000;
  height: 30px;
  width: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="openIt">Open Item</div>

Upvotes: 3

Related Questions