flen flen - 1 month ago 6
HTML Question

Make javaScript (not JQuery!) "activate" on keypress a CSS button:active style

Newbie here.

I have a similar code:

...
<style>
.button:active {
box-shadow: 0 5px #666;
transform: translateY(4px);
}
</style>
<script>
document.onkeypress = function(e) {
if (e.which === 115) { //this is the number code for the letter "S"
document.getElementById('start').click();
}
...
</script>
<body>
<input type="button" id="start" class="button" value="Start (S)" onclick="start();">
</body>


If I click on the above button everything works fine, but when I press the key "S" (keycode: 115) the function "start()" is called, but the CSS for active button doesn't start (that is, the animation for the button doesn't happen).

Question: How can I make the button:active animation start when I press "S", to make it look just as if I was clicking on the HTML button when I press the "S" key on my keyboard?

Please don't use JQuery in the answer, just plain JavaScript, since I'm not using JQuery libraries.

Thank you!

Answer

document.onkeypress = function(e) {
  if ((e.which || e.keyCode) == 115) { //this is the number code for the letter "S"
    document.getElementById('start').click();
    if (document.getElementById('start').className.indexOf("button-active") == -1) document.getElementById('start').className += ' button-active';
  }
};

document.onkeyup = function(e) {
  document.getElementById('start').className = document.getElementById('start').className.replace(/button\-active/g, "");

}

function start() {
  console.log("start")
}
<style>
  /*set button-active */
  .button:active,
  .button-active {
    box-shadow: 0 5px #666;
    transform: translateY(4px);
  }
</style>

<input type="button" id="start" class="button" value="Start (S)" onclick="start();" />

Comments