Do you have a CSS style that transforms the look of a button when clicked on-page? Want to extend this effect to when the button is activated via keyboard?
(In essence, browsers allow activating a button by pressing Tab to give it focus and then hitting Space. In addition, some browsers may convert an Enter press into submitting a form if one of its input fields has focus. This behavior is not officially defined but commonly observed. More details here.)
While applying the click effect using the :active
pseudo-class for mouse clicks is straightforward, testing revealed inconsistencies across different browsers regarding keyboard activation. Firefox 32 did not trigger the :active
pseudo-class with 'space', which was unexpected, whereas Chrome and IE behaved as expected. None applied the effect with the 'enter' keypress. To ensure consistent behavior, JavaScript had to be employed (using jQuery's $(xx).on()
). Any non-JavaScript/CSS-only methods to handle button effects upon keypress activation?
Here's a snippet of basic code: The complex buttons were simplified to just colored borders - colors change based on activation method in the real system:
$(document).ready(function() {
$("#form").on("keydown", function(ev) {
if (ev.which == 13) { // enter on form (submit)
$("#button").addClass("formenter");
}
});
$("#form").on("keyup", function(ev) {
if (ev.which == 13) { // enter on form (submit)
$("#button").removeClass("formenter");
}
});
$("#button").on("keydown", function(ev) {
if (ev.which == 32) { // spacebar while button has focus
$("#button").addClass("spacebar");
}
});
$("#button").on("keyup", function(ev) {
if (ev.which == 32) { // spacebar while button has focus
$("#button").removeClass("spacebar");
}
});
});
.mybutton {}
.mybutton:active {
border: 5px solid red;
}
.mybutton.spacebar {
border: 5px solid cyan;
}
.mybutton.formenter {
border: 5px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form" action="javascript:console.log('Clicked!');">
<button id="button" type="submit" class="mybutton">Go</button>
</form>