0

I want to make a custom event which I can use like

$('.entry').on('click', function().......

I need it for detecting a longtap for mobile devices. I want to call it like this:

$('.entry').on('longtap', function().......

I read a lot about creating events but the most ways are with bind and trigger. So is there a way to do this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

3 Answers3

2

Here is a way to implement long tap:

var clickStart;

document.getElementById("cool_button").addEventListener('mousedown', function() {
  console.log('mouse down');
  this.clickStart = new Date().getTime();
});

document.getElementById("cool_button").addEventListener('mouseup', function() {
  console.log('mouse up');
  if ((new Date().getTime() - this.clickStart) >= 1000) {
    console.log('this is a long tap');
  }
});
<button id="cool_button">i'm a long tap button</button>
Alon Yampolski
  • 851
  • 7
  • 15
0
  1. You may use one of the handmade solutions, provided here.
  2. You may attach it as third-party script.
  3. There is a special taphold event for jQuery Mobile.
Alex Stulov
  • 110
  • 1
  • 8
  • i cant use jquery mobile because it does many weird things to my frontend - also if i only use the js file without the css. i'll have a look to the third party script. it seems a good solution. – Daniel Zenker Jun 27 '19 at 06:37
  • i used the third party script which is very small and handy. i did some small modifications to fit my needs and so it works! Thanks to everyone! – Daniel Zenker Jun 27 '19 at 08:19
  • I'm glad this helped! – Alex Stulov Jun 27 '19 at 08:26
0

As said here , you don't need to create a custom event for longtap, you only need js timer and two already exsiting events like mouseup, mousedown:

var pressTimer;

$(".entry").mouseup(function(){
  clearTimeout(pressTimer);
  // Clear timeout
  return false;
}).mousedown(function(){
  // Set timeout
  pressTimer = window.setTimeout(function() {
  console.log("hi!")
  },1000);
  return false; 
});

I made an example for you

https://jsfiddle.net/sOoN92/74rbc2ph/