sigmaxf
sigmaxf

Reputation: 8502

Prevent same function from firing twice

I'm using jquery's bPopup() to open a modal window. When the user clicks a button, jquery loads an ajax page and then shows the modal windows. Due to this small delay when loading the page, the button remains active, and if the user clicks twice, it will fire twice, making two ajax requests to the server and opening two windows.

Is there a simple way to prevent this from happening? Since it's relatively a common problem, I wonder if there's a "right" way the pros handle it.

I've tried assigining the popup to a window.object, so that it would be overwritten on the second call, but it's still opening two popups.

Upvotes: 0

Views: 1012

Answers (1)

Amit
Amit

Reputation: 46361

That depends on what UX you're after, but I'd suggest you disable the button.

That way your user will:

  1. Know the click was "registered".
  2. Not try to click again.
  3. Not crash / confuse you code.

EDIT
According to the comment, the "button" is actually not a <button>, but an element with an onclick handler. So:

  1. You can disable the click handler by reversing what you did to set it (removeEventHandler, onclick=null...), but you'd then have to set it back once the pop-up is done, and that might be quite annoying.
  2. You'd have to somehow manipulate the UI to indicate the button was clicked and is disabled. Could probably be quite simple to do with a CSS class.

But really, you're probably better off having 2 "versions" of your button element (<div>...), with only 1 visible at a time, with the other hidden via display: none. The "clicked" version should not have a click event handler set at all. Then, when the button is clicked, you immediately switch between the 2 (can be done with a single CSS class), and once the pop-up is done, switch back.

Upvotes: 1

Related Questions