Prevent double clicking on a button

Processing postbacks can be a lengthy experience at times, if you need to do a lot of processing, or a confronted with a slow server. Users may be tempted to either click again, or just simply think they need to double click your button.

This tiny piece of javascript can be added to a page to prevent double clicking on an ASP.NET button. It hooks into the window.unbeforeunload event, that is called when a postback is started. This way the button is only disabled if you are sure that a postback will be processed, making sure the button will be re-enabled when the event or data has been processed and the button is presented again to the user.

<script type="text/javascript">
    function DisableButton() {
        document.getElementById("<%= ButtonSomeButton.ClientID %>").disabled = true;
    }
    window.onbeforeunload = DisableButton;
</script>