skip to Main Content

One button, detecting click and long press:

$('#button').on('click', function(e) {
  e.preventDefault();
  CLICK()
});

$('#button').on('mousedown touchstart', function() {
    LongPressTimer = setTimeout(function() {
      LONGPRESS()
    }, 1000)
  })
  .on('mouseup mouseleave touchend', function(e) {
    e.preventDefault();
    e.stopPropagation();
    clearTimeout(LongPressTimer)
  });

Click works, long press works.
But a long press also invokes a click.

What needs to be changed so that a long press does not invoke a click?

2

Answers


  1. Chosen as BEST ANSWER

    The answer is based on the ideas from Justinas and Epascarello above.

    $('#button').on('click', function(e) {
    e.preventDefault();
    if(DidLP) {DidLP=false; return false}
    CLICK()
    });
    
    $('#button').on('mousedown touchstart', function() {
    LongPressTimer = setTimeout(function() {
    LONGPRESS();
    DidLP=true;
    }, 1000)
    })
    .on('mouseup mouseleave touchend', function(e) {
    clearTimeout(LongPressTimer)
    });
    

  2. You can add a boolean to check if the event fired. I am using dataset to avoid all the extra global variables.

    const fncClick = () => console.log('click');
    const fncLong = () => console.log('long');
    
    $('#button').on('click', function(e) {
      e.preventDefault();
      if (!this.dataset.ignoreClick) {
        fncClick();
      }
    });
    
    $('#button').on('mousedown touchstart', function() {
        const btn = this;
        delete this.dataset.ignoreClick;
        btn.dataset.longPressTimer = setTimeout(function() {
          fncLong();
          btn.dataset.ignoreClick = true;
        }, 1000)
      })
      .on('mouseup mouseleave touchend', function(e) {
        clearTimeout(this.dataset.longPressTimer)
      });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button id="button">hm</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search