Reputation: 15866
Scripts
var timer;
var firing = false;
var begen = function(id) {
alert('one click');
};
var popupAc = function(id) {
alert('double click');
};
function cc(id) {
if (firing) {
popupAc(id);
clearTimeout(timer);
firing = false;
return;
}
firing = true;
timer = setTimeout(function() {
begen(id);
clearTimeout(timer);
firing = false;
}, 250);
}
Html
<div id="myID" onclick="cc()">Click Here</div>
Example: http://jsfiddle.net/LXSZj/11/
Question:
It works fine with ie and chrome, But in firefox, when I double click, I get two alert functions.(alert double click event and one click event)
How can I fix It?
Thanks.
Upvotes: 2
Views: 2689
Reputation: 3618
To control double click problems, i built this function, basically for every function you want to protect against the user clicking too fast, double click etc.. you call this function instead and define the timing range of release of the function. This is usefull to avoid API or endpoint calls that makes no sense or would be repetitive, or abusive in some cases.
The method_name parameter is just any label you desire, just in case you want to check the prevented array lists with console.log(runnning_methods);
Usage example:
var runnning_methods={};
function preventQuickMethod(method_name,callback,delay_time){
if(!delay_time){var delay_time=500;}
if(runnning_methods[method_name]==1){return;}
setTimeout(function(){ runnning_methods[method_name]=0; console.info(method_name+" released");},delay_time);
runnning_methods[method_name]=1;
callback();
}
function nextpage(){
preventQuickMethod("dismissSlot",function(){
document.getElementById("btn").innerHTML="fired at "+Date.now();
},1000);
}
<button onclick="nextpage()">Fire!</button>
<span id="btn" >EHHEHE</span>
Upvotes: 0
Reputation: 859
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var timer;
var x = false;
function myfun(){
if(timer){
clearTimeout(timer);
alert('double click');
timer = 0;
return;
}
timer = setTimeout(function(){
alert('singleclick');
timer=0;
clearTimeout(timer);
},250)
}
</script>
</head>
<body>
<p>If you singleclick/double-click on me, I will alert.</p>
<p> i will also alert based on your click</p.
<script>
(function(){
pelem = document.getElementsByTagName('p');
for(var i=0;i<pelem.length;i++){
pelem[i].addEventListener('click',myfun,false);
}
})()
</script>
</body>
</html>
Upvotes: 0
Reputation: 14521
Move your clearTimeout above the alert
clearTimeout(timer);
popupAc(id);
PS: I might be wrong, just guessing, not having firefox here..
Upvotes: 3