Frontend

Did a user click a button?

While working on a project I came across a situation where I needed to know if a button was clicked by a user or if it had been triggered by the code.

Lucky for us, the DOM is pretty friendly to us in this instance and offers us some help - the isTrusted property from the Event interface.

Let’s create a simple Ionic app and add in some HTML and Typescript to try it out.

<ion-content>
  <ion-item text-center>
    <ion-label class="ion-text-center">{{ source }}</ion-label>
  </ion-item>

  <br />

  <ion-button id="button" expand="block">
    User click click
  </ion-button>

  <ion-button (click)="onRobotClick()" expand="block">
    Robot click
  </ion-button>
</ion-content>

We have a simple label which will hold the source of our clicks and two buttons.

Let’s now add some typescript code to handle all the different clicks.

export class HomePage implements OnInit {
  source: string;
  constructor() {}
  
  ngOnInit(): void {
    document
      .getElementById('button')
      .addEventListener('click', (event: Event) => {
        this.setSource(event.isTrusted)
      })
  }

  onRobotClick() {
    document.getElementById('button').click();
  }

  setSource(isTrusted: boolean) {
    this.source = isTrusted ? 'User' : 'Robot'
  }
}

We will add an eventListener on our first button and then monitor what happens with him.

Clicking the button itself will trigger a regular event which we will handle with the event listener and check for the isTrusted property which should be set to true.

If we click the second button we will executed a different function which will grab the element by its id and execute a click which should result in the isTrusted being set to false.

In both cases we will call the setSource function which will get the property and display if a user or robot clicked on the button.

click-gif.gif

As you can see above, clicking the button directly results in the isTrusted property being true so the app displays, correctly, that a user clicked on the button. Clicking the other button triggers a programmatical click on the HTML element which results in the property being false which is indicated by the label changing to Robot.

As always, you can get the code from github.

That’s it for today.

Until next time,
Happy coding