Reputation: 139
Can someone help me get started with a button timeout feature. All I want is a button (when clicked) it becomes inactive for 2 seconds. After which it is active again.
Upvotes: 1
Views: 39391
Reputation: 1189
You can use setTimeout() function in javascript. Something like
<html>
<head></head>
<body>
<input id="test" type="submit" value = "clickme" onclick="deactivatefunc()">
<script type="text/javascript">
function deactivatefunc()
{
var btn = document.getElementById("test");
btn.disabled = true;
var mytimer = setTimeout(activate,2000);
}
function activate () {
var btn = document.getElementById("test");
btn.disabled = false;
}
</script>
</body>
</html>
Upvotes: 0
Reputation: 47776
The function setTimeout
allows you to specify a function to be called after an amount of milliseconds has passed. In this case, I passed in an anonymous function, that is, a function that does not have a name that is used for the sole purpose of re-enabling my button after 2 seconds.
var mybutton = document.getElementById("mybutton");
mybutton.onclick = function() {
mybutton.disabled = true;
setTimeout(function() {
mybutton.disabled = false;
}, 2000);
};
Upvotes: 1
Reputation: 324600
Start of with:
<button>Click me!</button>
Add an event:
<button onClick="...">Click me!</button>
Now we need to put something in place of that ...
.
this
can be used to mean "the button that was just clicked"
this.disabled
can be set to true
or false
to disable (or re-enable) the button.
setTimeout(function() {...},2000);
executes the anonymous function after two seconds have passed (or as near as the timer resolution allows).
Again, need to put something in the ...
. I've already told you how to re-enable the button.
Although, since this
isn't terribly reliable inside anonymous functions, it's probably better to start with var t = this;
and use t
to mean the button.
With all that in place, you have:
<button onClick="var t = this; t.disabled = true; setTimeout(function() {t.disabled = false;},2000);">Click me!</button>
Done. I hope this explanation was helpful.
PS. To those who are against inline event handlers:
Upvotes: 2