I\'m attempting to write a video poker game in Javascript as a way of getting the basics of it down, and I\'ve run into a problem where the jQuery click event handlers are f
All the stuff about .on() and .one() is great, and jquery is great.
But sometimes, you want it to be a little more obvious that the user isn't allowed to click, and in those cases you could do something like this:
function funName(){
$("#orderButton").prop("disabled", true);
// do a bunch of stuff
// and now that you're all done
setTimeout(function(){
$("#orderButton").prop("disabled",false);
$("#orderButton").blur();
}, 3000);
}
and your button would look like:
<button onclick='funName()'>Click here</button>
Another solution I found was this, if you have multiple classes and are dealing with radio buttons while clicking on the label.
$('.btn').on('click', function(e) {
e.preventDefault();
// Hack - Stop Double click on Radio Buttons
if (e.target.tagName != 'INPUT') {
// Not a input, check to see if we have a radio
$(this).find('input').attr('checked', 'checked').change();
}
});
https://jsfiddle.net/0vgchj9n/1/
To make sure the event always only fires once, you can use Jquery .one() . JQuery one ensures that your event handler only called once. Additionally, you can subscribe your event handler with one to allow further clicks when you have finished the processing of the current click operation.
<div id="testDiv">
<button class="testClass">Test Button</button>
</div>
…
var subscribeClickEvent = function() {$("#testDiv").one("click", ".testClass", clickHandler);};
function clickHandler() {
//... perform the tasks
alert("you clicked the button");
//... subscribe the click handler again when the processing of current click operation is complete
subscribeClickEvent();
}
subscribeClickEvent();
If you're calling that function on each "click", then it's adding another pair of handlers on each call.
Adding handlers with jQuery just isn't like setting the value of the "onclick" attribute. One can add as many handlers as one desires.
$('.bed').one(function(){ })
Docs:
http://api.jquery.com/one/
If you find that .off() .unbind() or .stopPropagation() still doesn't fix your specific issue, try using .stopImmediatePropagation() Works great in situations when you just want your event to be handled without any bubbling and without effecting any other events already being handled. Something like:
$(".bet").click(function(event) {
event.stopImmediatePropagation();
//Do Stuff
});
does the trick!