Skip to content Skip to sidebar Skip to footer

Spacebar Triggering Click Event On Checkbox?

If you spacebar on a checkbox, it checks the box. Everything was fine until I decide to disable the click event on the parent div, which I realized, disabled the spacebar on the ch

Solution 1:

Quirksmode - click, mousedown, mouseup, dblclick

The click event fires when the user clicks on an element OR activates an element by other means (i.e. the keyboard) ... “click” event is really a misnomer: it should be called the “activate” event.

To work around this, you can attach a clickandkeyup event to the checkbox.

checkbox.addEventListener("click", handleCheckboxEvent, true);
checkbox.addEventListener("keyup", handleCheckboxEvent, true);

Listen to both events, and always disable the default behavior. From there, you can determine if the spacebar fired a keyup event if the key 32 is pressed (e.keyCode === 32).

If so, manually check the checkbox if it is not checked, and uncheck it if it is checked.

functionhandleCheckboxEvent(e) {
    e.preventDefault();

    if (e.keyCode === 32) {  // If spacebar fired the eventthis.checked = !this.checked;
    }
}

Updated Example - tested in the latest versions of Chrome/FF/IE.

(function () {
    var checkbox = document.getElementById('checkbox');

    functionhandleCheckboxEvent(e) {
        e.preventDefault();

        if (e.keyCode === 32) {  // If spacebar fired the eventthis.checked = !this.checked;
        }
    }

    checkbox.addEventListener("click", handleCheckboxEvent, true);
    checkbox.addEventListener("keyup", handleCheckboxEvent, true);
})();
<inputid="checkbox"type="checkbox" />

Solution 2:

Kaiido seems to have a good solution. As for the behavior this is apparently expected. According to:

W3C - SCR35: Making actions keyboard accessible by using the onclick event of anchors and buttons

the onclick event is triggered by the keyboard for accessibility purposes. Browsers use the click event even if its triggered from the keyboard in the event that a mouse isnt present:

While "onclick" sounds like it is tied to the mouse, the onclick event is actually mapped to the default action of a link or button. The default action occurs when the user clicks the element with a mouse, but it also occurs when the user focuses the element and hits enter or space, and when the element is triggered via the accessibility API.

Post a Comment for "Spacebar Triggering Click Event On Checkbox?"