I am creating a dynamic quiz and I need to prevent multiple clicks on my 'next' button. In the click function I tried to an if
condition to prevent multiple clicks. Not sure why it doesn't work. Would greatly appreciate some help.
var nextButton= $('<button/>', {
text: 'Next',
id: 'nextButton',
click: function (event) {
event.preventDefault();
if($("#container").filter(':animated').length>0) {
return false;
}
/* rest of code*/
}
});
Here is the code as it appears my JSFiddle of my application
Bonus Question: I was told event.preventDefault()
is good practice. Is this true? If so, why?
Update: The JSFiddle line # where the code above is line 81 in case you want to mess around with the code without digging through it all.
There are a number of ways to allow only one-click in Javascript: Disable the button after clicking on it. Use a boolean flag to indicate “clicked”, don't process again if this flag is true. Remove the on-click attribute from the button after clicking once.
var nextButton= $('<button/>', {
text: 'Next',
id: 'nextButton',
click: function (event) {
event.preventDefault();
if($("#insideContainer").filter(':animated').length>0) {
return false;
}
/* rest of code*/
}
});
I found out why. You're checking against the wrong element. It should be #insideContainer
Demo
Try like this
$("#id or .class").one("click",function(){
// your activity
});
Description:
The one() method attaches one or more event handlers for the selected elements, and specifies a function to run when the event occurs.
When using the one() method, the event handler function is only run ONCE for each element.
One way to do this to use timeStamp
property of event like this to gap some time between multiple clicks:
var a = $("a"),
stopClick = 0;
a.on("click", function(e) {
if(e.timeStamp - stopClick > 300) { // give 300ms gap between clicks
// logic here
stopClick = e.timeStamp; // new timestamp given
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With