When you click on a
<button> element, it usually does a visual effect in response to the keypress. I’ve created a
<button> element, let’s call him “Button”.
press() is called.
press just prints “pressed” to the console.
I’ve also set it up so that, when I press any key on my keyboard, Button is “clicked” as well (i.e. pressing a key triggers a ‘click’ event for Button). This calls
press() so that in the console I again see “pressed”. Here’s my CodePen test for this.
Notice that if you “click” on Button with your mouse, the visual
<button> effect plays, but if you just press a key (which should “click” button as well), this visual effect does not play. How can I make it so that the visual effect plays even when I only press a key? I had thought that it would happen if I used the ‘click’ event.
It hasn’t been clicked in that case, you need to look at the “keydown” and “keyup” events (which [natch] listen for a key being pressed down, and a key being released)
I believe you are referring to the styling change that happens when you click the button with the mouse? This is caused by styling on the
:active selector for the button (which your browser provides default values). I don’t think this is something you can directly manipulate with JS. In other words, simulating a mouse click with JS will not affect the status of the
:active state on the button.
I think you will have to handle this yourself manually. You’ll probably want to listen for separate keydown and keyup events and then add/remove a class on the button and then you can style the button to looked pressed when that class is on the button. You could also override the
:active selector on the button to use those same styles so that the button press looks the same for both mouse clicks and button presses.
Ahh, I see @DanCouper has beaten me too it. What he said.
I soon realized after posting this that the visual effect is related to the mouse being pressed down on the button, and that led me to the :active selector that you mention.
After looking it up, it looks like you can’t modify pseudo-classes with jQuery, so I’ll use the solution of adding/removing a class with keydown/keyup to mimic the
:active selector. Thanks to both @DanCouper and @bbsmooth!
Just to be clear, it’s not just a jQuery thing, you can’t do this with JS at all. Simulating a click event is not exactly the same as actually clicking on something. It will fire the click event but it won’t trigger the
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.