9

What is the best way to hide an element using A-Frame?

Do I need to remove the element from the DOM?

David Walsh
  • 264
  • 1
  • 4
  • 6

4 Answers4

10
var el = document.querySelector("#yourElementId");

el.setAttribute("visible",false);
ffmaer
  • 751
  • 9
  • 17
3

The easiest way to hide an element is the visible attribute:

myElement.setAttribute("visible", false)

boxtrain
  • 2,458
  • 1
  • 11
  • 20
David Walsh
  • 264
  • 1
  • 4
  • 6
2

You can also specify it on the a-frame tag itself e.g.:

<a-image id="hand-overview-chart"
  src="#handOverviewImg" position="3 3 0"
  width="4" height="4" visible="false">
</a-image>

Of course you'll still need javascript to trap on some event like "mouseenter" to toggle it visible:

document.querySelector('#myElParentId').addEventListener('mouseenter',myEventHandler); 

myEventHandler: function (evt) {
  let myEl = document.querySelector("#hand-overview-chart");
  myEl.setAttribute("visible","true");
}
vt5491
  • 2,254
  • 2
  • 22
  • 34
1

The problem with visible="false" is that the element behind it will not be clickable (because the element is there, but is transparent). So, the alternative I found is to make it with zero width. Here is how I hide the element on mouse click:

document.getElementById("my_element_id").addEventListener('mousedown', function(evt) {
  document.getElementById("my_element_id").setAttribute("width", "0");
});
  • Most A-Frame entities don't have a width attribute. Only a few (such as do. You can solve the issues about what is / is not clickable by appropriate settings on the raycaster object. I wonder whether your answer is really applicable to A-Frame entities, or if you had 2D DOM elements in mind with this suggestion? – Diarmid Mackenzie Mar 04 '22 at 21:55