I have a small snippet of code which I use to toggle the checked
property of a checkbox when the space bar is pressed.
$(document).on('keydown', function(e) {
if (e.which === 32) {
e.preventDefault();
$('#example').prop('checked', function() {
return !this.checked;
});
}
});
The above works fine in Chrome v30 and IE10, but not in Firefox v24. The problem occurs when you click the checkbox, and then use the space bar to toggle it, it momentarily checks it, and then unchecks it, and vice versa.
I believe the problem has something to do with the fact that the click
event is triggered in Firefox when using keydown()
, despite using e.preventDefault()
(which prevents the click event from triggering in both Chrome and IE).
I tried using the same code, binding the keyup
event. This fixed the problem in Firefox, but then introduced the same problem to IE.
Here's the fiddle where Firefox is affected
Does anybody know why this is happening, and how I can get around it?