Reputation: 1936
I am trying to disable multiple clicks on element or set a delay between each click to prevent content overloading
I am thinking to do something like this:
var clicked = false;
if(!clicked)
{
clicked = true;
// do all my stuff right here !!
setTimeout(function(){
clicked = false;
}, 3000);
}
But it's not working. Can anyone offer any suggestions?
Upvotes: 4
Views: 17360
Reputation: 51
I put the following code at the beginning of my main js script:
let clicked = false; //global variable
function prevent_double_click() {
clicked = true;
setTimeout(function() {
clicked = false;
}, 1000);
}
Then each function where you want to prevent the double click looks like this:
function myFunction() {
if (clicked) return;
prevent_double_click();
//your code here
}
That way you won't be able to click again after 1 second.
Upvotes: 0
Reputation: 888
This won't work because the clicked variable is in function scope. You need closure for that. Below would help if you want to do this via a variable. You can set html5 data attributes also to handle the same.
Working JSFiddle here
window.onload = function() {
initListener();
};
var initListener = function() {
var clicked = false;
document.getElementById('btn').addEventListener('click', function(event) {
if (!clicked) {
clicked = true;
alert('Hi');
setTimeout(function() {
clicked = false;
}, 3000);
}
}
);
}
Upvotes: 1
Reputation: 22323
Disable to click your button for 30 second using setTimeout
.
$("#btnTest").click(function() {
$(this).attr("disabled", true);
setTimeout(function() {
$('#btnTest').removeAttr("disabled");
}, 30000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' id='btnTest'>
Upvotes: 2
Reputation: 1097
I supoppose you init clicked variable outside click function, otherwise if condition always be true on each click.
Without using jQuery this code works:
var clicked = false;
function clickEvent() {
if(!clicked)
{
clicked = true;
console.log('clicked!!');
setTimeout(function(){
clicked = false;
}, 3000);
}
}
<button onclick="clickEvent()"> Click me twice</button>
Upvotes: 1
Reputation: 1996
you can disable element
$(element).prop('disabled', true);
after clicking it
Upvotes: 4