How do I properly restrict a .on('click tap') event from triggering more than once per click?

75 views Asked by At

I'm developing an application on Phonegap with a screen that has a Cancel button.

The Cancel button needs to have a click/tap event listener that cancels the form submission and returns to the previous page on the application.

The application needs to be compatible with both mobile devices (such as tablets) and modern day browsers. Which is why I listen for both click events as well as tap events.

This is how I have the event listener defined...

$(cancel_button).on('click tap', function(event)
{
    // I assumed the following line would fix the issue, but it doesn't.
    event.stopImmediatePropagation();

    GoBack();
    alert("Your submission has been cancelled.");
});

So when I click the cancel button on a browser it runs the code inside the listener about 6 times. Anyone have an idea on how to solve this?

2

There are 2 answers

0
Eric On

Maybe try

$(cancel_button).on('click touchend', function(event)
{

    event.preventDefault();

    GoBack();
    alert("Your submission has been cancelled.");
});
0
Ricky On

To anyone who might run into an issue similar to this...

I ended up researching into a JS Plugin called Hammer.js

It resolved the issue with ease, I ended up creating a wrapper function that can be used to create a HammerEvent for the tap and press event types with it.

Solved my problem, and works perfectly!

I highly recommend looking into Hammer.js, I'm going to be converting all my click events so that it uses Hammer.js.