'A-frame button onClick changes object

I'm trying to create something in A-frame (aframe.io) where when a button onclick event happens, a cube will change colors. Here is my current code:

 <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
<button style="z-index: 999; position: fixed">RESIZE</button>
<script>
  AFRAME.registerComponent("foo", {
    init: function() {
      const btn = document.querySelector("button");
      const sphere = document.querySelector("a-sphere");
      btn.addEventListener("click", e => {
         sphere.setAttribute("color","red");
      })
    }
  })
</script>
<a-scene foo>
  <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>
</a-scene>

The code here works perfectly but its not using an onclick event. How can I change the code above so when there is an onclick function on the button and when that function occurs the color changes? Just clarifying, I know the code above is working perfectly but it's using an event listener to tell when the button is being clicked, I need to change that to an onclick event.



Solution 1:[1]

If you wish to use normal JS (onclick) instead of all register components then you can try something like this

<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
    <button style="z-index: 999; position: fixed" onclick="s()">RESIZE</button>
    <a-scene foo>
        <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>
    </a-scene>
<script>
    function s(){
        const sphere = document.querySelector("a-sphere");
        sphere.setAttribute("color","red");
    }
</script> 

you can call a function s and that function will set attribute for color

Solution 2:[2]

Define a variable s, then, when the AFRAME has initialized, assign a function which changes the color of the sphere to it. Attach an onclick event to the button which then calls the function s.

var s;
AFRAME.registerComponent("foo", {
  init: function() {
    const sphere = document.querySelector("a-sphere");
    s = function() {
      sphere.setAttribute("color", "red");
    }
  }
})
console.clear();//<-- this is to get rid of the console logs which clog up the snippet view
<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
<button style="z-index: 999; position: fixed" onclick="s()">RESIZE</button>
<script>
</script>
<a-scene foo>
  <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>
</a-scene>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ajai.s
Solution 2 Spectric