6

I have this html button:

<button
    type='button'
    class="button-name" 
    (click)="change($event)"
    [disabled]='disabledButton'
>

I have this in typescript:

change(event: Event) {
    console.log(event);
}

The problem is that when I hit ENTER on this button when is focused, it will trigger MouseEvent instead of Keyboard Event:

MouseEvent {type: "click", target: ..., ...}

Why does it fire MouseEvent on Enter? What's the best way to change it? The button should definitely works on both keyboard and mouse but because of some tracking and a11y running in the background, this results in incorrect behaviour.

Thanks anyone who can explain further why it is MouseEvent and suggest some solution.

0

2 Answers 2

8

It's the default browser behavior to trigger a click event when the enter key is pressed while a button is focused or if it's of type submit and the enter key is pressed while some element of a form is focused.

But you can easily detect if it's an actual click by the user because the event.detail of a mouse event holds the actual click count otherwise it's always zero. See UIEvent.detail.

Sign up to request clarification or add additional context in comments.

1 Comment

This really worked for me. I checked event.detail and if found 0 I returned back:- if(event.detail == 0) return;
2

That probably has to do with the JS engine behind the browser, that considers the button to be clicked when a key like enter or space is pressed ?

Anyway, to resolve that, simply bind both click and keydown.enter/keyup.enter

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.