Wednesday, November 17, 2010

SetTimeout to temporarily disable buttons

Normally you would call the function and pass a callback function name to it so that at the time out event your function will be called.

Now what if I want to use the same call back function to act on different DOM elements? For example, I want to disable the button for a few seconds when I click on it. The disabling is to prevent user from clicking on it multiple times. The problem is that there are a few buttons of similar nature that acts differently on clicking. Instead of having to create different callback functions for each button, I want to use the same function for all the buttons.

It turned out that this could be done.

In your INPUT create a "onclick" event by calling a function and pass "this" as parameter.

In the called function do the following

myattribute=document.createAttribute("disabled")
myattribute.nodeValue=true
param.setAttributeNode(myattribute)
settimeout(function(){mycallback(param)},1000)

The first three lines will disable the button. The fourth line will call the timeout with mycallback as function. It is actually a dynamic function that calls mycallback function by passing the INPUT object as parameter. This means that the script still creates different functions for each button but it will not be created till user clicks on it. Coding wise this is easier to maintain than you create all the functions manually.

mycallback will then be able to act on the "param" (which is the "INPUT" object) by calling

param.removeAttribute("disabled")


No comments:

Post a Comment