Home > Mobile >  Trigger a button click when the space bar is pressed
Trigger a button click when the space bar is pressed

Time:08-05

Now using (click) on the button, but how i want to use click and enter/space bar too.

<button #casinoShuffle id="casinoShuffle" type="button" (click)="ShuffleClick()"
[style.background-color]="Eveluck?.spinButtonColor"
[style.border-color]="Eveluck?.spinButtonColor"
>{{this.Eveluck?.spinText}}</button>

CodePudding user response:

Add keydown.Space event listener

<button #casinoShuffle id="casinoShuffle" type="button" (click)="ShuffleClick()"
(keydown.Space)="ShuffleClick()"
[style.background-color]="Eveluck?.spinButtonColor"
[style.border-color]="Eveluck?.spinButtonColor"
>{{this.Eveluck?.spinText}}</button>

CodePudding user response:

You do not need to do anything, the browser already does that for you.

<button> and <a> elements are natively focusable, f.e. by means of the Tab key, and the browser will dispatch a click event when users use Enter or Space.

Activation behavior of elements of the HTML spec explains:

The user agent should allow the user to manually trigger elements that have an activation behavior, for instance using keyboard or voice input, or through mouse clicks. When the user triggers an element with a defined activation behavior in a manner other than clicking it, the default action of the interaction event must be to fire a click event at the element.

On macOS users can opt for skipping <a> links in the tab sequence.

You could manually bind to (keydown.Space)="ShuffleClick()" to do something else, but that is a bad idea since users’ expectation is for the button to do the same thing when clicked and activated by means of keyboard.

  • Related