1

:active pseudo-class w/keypress event.


I have svg buttons I drew for a drum machine I'm working on. I use a css :active to change their x: and y: when :active with 'click tap' event, they also play a sound. i have bound them to keyboard as well. i can't figure out if i can add active pseudo class somehow so keypress acts like mouse click.


I researched and didn't find much. what I did come across was vague and not exactly what I am trying. I'm using jquery. I did come up with another solution which is a addClass tied to a keyframes with a setTimeout that does get the effect I want. I just want to know if there is a more efficient way to control :active.


My Codepen


I would want to simply add active instead of doing separate animation for 20 buttons. My code works it just seems like their would be an easier way, and I would like to know it.


$(document).keydown(function(e) {
switch(e.which) {
    case 40:bass.play();
            screen.text("bass drum");
            $("#btnright").addClass("test");
            setTimeout(function()                                                       
  {$("#btnright").removeClass("test");},200);
    break;

    case 32 :snare.play();
            screen.text("snare drum"); 
    break;

    case 39: high

And some of the CSS


    #btnright:active{
  x:-304;
  y:-468;
}
.test{
  animation: test .2s linear; 
}
@keyframes test{
  0%{}
  50%{x:-304; y:-468;}
  100%{}
}

To see the effect I want use the down arrow. I should also say sorry if this is an ignorant question. I am a total noob saibot.

benjaminadk
  • 468
  • 6
  • 18

1 Answers1

0

It's not possible to modify pseudo-classes using JavaScript so you'll need to toggle an active class.

Example

JS

var $btn = $('#btn')
$(document)
.keydown(event => {
    $btn.addClass('active')
})
.keyup(event => {
    $btn.removeClass('active')
})

CSS

#btn:active,
#btn.active {
 ...
}

Codepen Demo

Resources:

Miguel Mota
  • 20,135
  • 5
  • 45
  • 64