Blocking multiple clicks real easy
by ricardoz on Aug.10, 2009, under JavaScript, Performance, Security, Web related
I’ve faced this problem a few times before, but this time I decided to find a generic solution to it. I needed to prevent users from clicking action links in a web application multiple times and therefore triggering some server side action a lot of times when only one time was enough/needed.
After looking around for a few hours for an elegant solution I just couldn’t find one, all the articles/answers I found required controls on each link and/or special handling on the server side code that reacted to them.
Well, after a few days of intense thinking (or something like that) I came up with a short and simple piece of Javascript code that seems to work wonderfully.
Basically what it does is wrapping the onclick event with a control mechanism that does nothing if the object was the last one clicked and a pre-defined timeout hasn’t expired. Check out the code if you want to understand it’s inner workings, it’s quite simple and short.
What I like the most about this approach is that it’s independent from the actual page content and behavior, its quite unobtrusive and it doesn’t affect your page performance by using timeouts or checking loops.
To use it you just have to include it in your HTML pages, using something like:
<script type="text/javascript" src="multiclickblocker.js"></script>
Additionally, if you want you can edit the multiclickblocker.js file and define which objects you want to protect (TO_BIND) and how long should the block last (BLOCK_TIMEOUT).
I’ve tested it with Google Chrome, Firefox 3 and Internet Explorer 8 and it worked just fine, leave a comment if you have any problems with it.
You can download it and a very simple sample here.
PS: The script is based on jQuery, so you will need to include it in your pages as well. I developed and tested it using v1.2.3.
September 29th, 2009 on 6:49 pm
You are a life saver… you have no idea how long I have struggled with this problem. Thanks for sharing.
October 22nd, 2009 on 12:05 pm
Very useful information. Thanks for the java script. I will test it on my project.
cheers