I have an object in my scene and I would like it so that when I click on the object, a function called myFunction occurs. How can this be done? I have also assigned an id of #plane1 to my object in case that could help with the function. How can I have it so when I click on the object #plane1, a function called myFunction occurs?
1 Answer
Well you can use the onclick event on an HTML element. So for example:
<div id="plane1" onclick="myFunction()">Click me</div>
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
OR
You use addEventListener() if you want to add the event using JavaScript. So for example:
const plane = document.getElementById("plane1");
plane.addEventListener("click", myFunction);
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
3 Comments
Aidan Young
The code usually works in A-frame but for some reason it isnt working with my <a-entity> I'm not sure why though, is there another way? My code Fiddle: jsfiddle.net/AidanYoung/h0cb1nq8/2
Dang Khoa Chiem
Well this page talks about events in the A-frame library (aframe.io/docs/1.2.0/introduction/…), however, I'm not an expert of this library so I do not know exactly why it doesn't work.
Dang Khoa Chiem
In the bottom of the events section it says: A common misbelief is that we can add a click event listener to an A-Frame entity and expect it to work by directly clicking on the entity with our mouse. In WebGL, we must provide the input and interaction that provides such click events. For example, A-Frame’s cursor component creates a synthetic click event on gaze using a raycaster. Or as another example, Mayo Tobita’s mouse-cursor component creates a synthetic click event when clicking directly on the entity using a raycaster.