9.5 Blocking Double Clicks

NN 3, IE 4

9.5.1 Problem

You want to prevent a second click on a button or link.

9.5.2 Solution

Use the onclick event handler of the button or link to carry out the intended single-click action, and then redirect the event handler for any subsequent click. For example, the following link submits a form by way of the submitForm( ) function:

<a href="#" onclick="return submitForm( )">Submit</a>

In the event handler function, reassign the function to a second function that performs no action:

function submitForm( ) {
    document.forms["myForm"].submit( );
    submitForm = blockIt;
    return false;
}
function blockIt( ) {
    return false;
}

9.5.3 Discussion

Notice that this recipe makes no mention of the ondoubleclick event handler. That's because the event is irrelevant for this kind of blocking operation. If you don't script an ondoubleclick event handler, nothing happens when that event fires. You want to prevent a subsequent click event. This is especially important for form submissions in applications such as e-commerce transactions. If the user clicks the Submit button a second time while the form page is still visible, the server may process both submissions and store the order in the database twice.

The technique shown in the Solution is deceptively simple. The second statement of the submitForm( ) function equates the submitForm( ) function with the blockIt( ) function. The next time that submitForm( ) is invoked, the blockIt( ) function is invoked in its place. Bear in mind that this function reassignment stays in force unless the page reloads.

If you wish to script an action to occur upon double-clicking an element, you can use the ondoubleclick event handler. But attempting to script both the onclick and ondoubleclick event handler for the same element will lead to unsatisfactory results. At best, you can combine ondoubleclick event handlers with onmousedown or onmouseup event handlers, just like real applications do.

9.5.4 See Also

Recipe 9.4 for blocking the default behavior of an event.