Solving Javascript multiple click event trigger bug

The past couple of days I have been struggling with a Javascript bug in Passbook that had left me scratching my head. One of the GUI controls for editing password group names has two linked images that are attached to the on click events for editing and deleting a group name. The controls are destroyed and replaced with an input box with save and cancel buttons and restored upon cancel. The bug occurs when cancel is pressed and the edit & delete controls are re-bound to their required click events. The GUI code is similar to the following:

<a href="#" class="edit"><img src="edit.png"></a>
<a href="#" class="delete"><img src="delete.png"></a>
The code is dynamically saved (along with the static group name) as an invisible attribute in the containing div and is not altered at all. The bug however occurs when the code is restored. What happens is when edit.png is bound to function edit(e) and delete.png is bound to del(e), when edit.png is clicked edit(e) and del(e) functions are both triggered while when delete.png is clicked only del(e) is triggered.

Even at this time I have no idea what is the cause of the bug. However the fix is quite simple. After playing around with global flags and setTimeout flag reset I discovered a simple check to ensure that the event is being intentionally triggered. The trick is to check which will be undefined for del(e) when edit.png is clicked because it was not actually triggered by the user but by either a browser or html bug. While I did not test it, a check for only should work fine for this problem as well.

Hopefully this tip can save you a lot of time as I tried Googling for a solution for about just as long as I tried to code a solution for it my self, shifting around the link/image positions, adding separator divs, and other crazy solutions to no avail. Unfortunately the trick to solving these kinds of problems are not always clear however the general rule should always be to check whatever data is available; doing that would've saved me at least 3 hours.


Unknown said...

Where are your closing tags for the A tags?

Paul Chiu said...

Sorry, they were there before, just got forgotten when I retyped the code as HTML.

Post a Comment