How to handle click events on AR.js

Showing AR content on a website is nice, but adding user interaction opens a completely new world of opportunities.

In the past articles I wrote about AR.js and the way we can deliver AR content only with a QR-Code. But what about interacting with 3D objects, that we can already show to the user? This will open a new world of applications for this wonderful technology.

A brief search on AR.js Github repository shows several event-related issues, most of them not solved. AR.js is built at the top of aframe and it’s not easy to understand how to handle simple events on 3D objects, i.e. click events.

I tried to collect all the working hints that I found and organize them into this article that comes with full working example of an user-interaction click.

So, let’s start!

Create the HTML entry point

As always, an AR.js app starts with an HTML file that defines markers, models, and so on. In this file, in order to handle events, we need to define additional properties on elements. Let’s see them in detail.

  • At line 10, we import an external Javascript file used for setting the event handler. We’ll see it later in detail
  • At line 21, our marker is defined with additional properties: markerhandler is used as the registered component name, while emitevents and cursor define the possibility to emit events, specifically mouse/touch based
  • It’s important to define an id or adding a very specific CSS class in order to retrieve our marker and entity elements later.

Let’s see how our events.js file looks

I already commented inline, and code is pretty self-explained: we register our component and, at the initialization, we add an event listener at ‘click’.

At line 8 I added an extra check: in fact, without that check events are firing multiple times, one for marker and one for entity. With this check we respond to an event only when cursorEl, our marker element, is visibile and is the element associated to the event.

That’s it! Once inside the event listener you can do whatever you want; I make the 3D model growing bigger each click. You can surely do something more interesting and useful than that :)

Chialab is a design company. By developing strategy, design, software and content, we generate exciting relationships between brands and people.