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.

Nicolò Carpignoli
Chialab Open Source
3 min readAug 8, 2018

--

This is part of a series of articles about AR.js. The following is the list of the articles written so far:

For the latest news about AR.js and Web AR, you can follow me!

Disclaimer: AR.js v3 is out, with a new Documentation that can be found at: https://ar-js-org.github.io/AR.js-Docs/. Learn more there if you found problems with this tutorial.

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 10 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 :)

Edit: I’m currently working to make this article updated to new a-frame versions and to answer to all of you asking for details about this topic. Stay tuned!

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

https://www.chialab.it.

--

--