U
U
uuushka2015-11-24 17:46:19
css
uuushka, 2015-11-24 17:46:19

How to use :active pseudo-class on keypress?

The bottom line is that there is a component that changes style when you click on it with the mouse using the :active pseudo-class.
I need to do the same behavior for the key. That is, when the key is pressed, the style changes, when it is released, it returns to its original state. I've wasted a lot of time, unfortunately.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Kravchenko, 2015-11-24
@mydearfriend

you need to track the keydown and keyup events, add and remove classes on the necessary elements
UPD
I won’t write for react, an example with jquery

var $elementToHighlight = $('#someId');
$(document).on('keydown',function(e){
  if(e.keyCode==13){
    //enter
    $elementToHighlight.addClass('hightlighted');
  }
}).on('keyup',function(){
  $elementToHighlight.removeClass('hightlighted');
});

U
uuushka, 2015-11-24
@uuushka

Dmitry Kravchenko , i.e. Something like this:

handleOnKeyUp() {
  this.setState({isPressed: this.state.isPressed})
};

handleOnKeyDown() {
  this.setState({isPressed: this.state.isPressed})
};

render(){
    var style = classNames({
       "pressed-style": this.state.isPressed,
       "unpressed-style": !this.state.isPressed    
})
     return  <button className={style}
                 onKeyUp={this.handleOnKeyUp}
                 onKeyDown={this.handleOnKeyDown}
                 >Button</button>;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question