2

I have a CSS style that changes the appearance of a (on-page) button while it is clicked. I would like to apply the same effect to the button when it is activated via the keyboard.

(To recap: a button may be activated in a browser by pressing Tab until the button has focus, then pressing Space. Additionally, although it seems not to be officially specified, many browsers convert an Enter keypress to an activation of the (a) submit button provided that one of the input fields in the form has focus (excluding multiline text areas, for obvious reasons). More details in this Stackoverflow answer. )

It is easy enough to apply the effect for mouse clicks with with the :active pseudo class. Some quick tests using Firefox 32, Chrome 41, and Internet Explorer 11 on Windows showed that FF did not apply the :active pseudo class when activating the button with Space (which seems irregular), while Chrome and IE do in fact apply it (which is what I would expect). None apply it when activating the button (inside <form>, type="submit") via Enter. To obtain consistent application of the effect on a keypress, I was forced to go the JavaScript route (jQuery $(xx).on() event handler simplifies things).

Is there a non-JavaScript/CSS-only way to handle button effects on keypress activation? My guess is no, but would like hear other insights/experiences...

Here is some basic code: (The more complex button effect was replaced with a simple colored border, for simplicity sake. The colors are changed depending on the activation method, for more clarity - in the real system, they would all be the same style.)

$(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>
Community
  • 1
  • 1
frIT
  • 3,213
  • 1
  • 18
  • 22

1 Answers1

1

Please check this

$("#button").bind('change keypress', function(e){
  // your code
});

Other wise you could get relevent similar example here:

Change event not firing when radio button is selected with keyboard

Community
  • 1
  • 1
Hoja
  • 1,057
  • 1
  • 12
  • 32