Search code examples
javascripthtmlaframe

A-entity with newly created components


I'm trying to include a newly registered component together with a component that provides a behavior inside an a-scene.

First, I register a component to change the color on hover. Then, I register a component to create a new circle.

When I create the entity inside the a-scene, it should show the hover-behavior, but it doesn't.

<html>
  <head>
    <script src="https://aframe.io/releases/0.9.2/aframe.min.js"></script>
    <script>
// here, I register the component to change color on hover
      AFRAME.registerComponent('change-color-on-hover', {
        schema: {
        color: {default: 'red'}
        },

        init: function () {
          var data = this.data;
          var el = this.el;
          var defaultColor = el.getAttribute('material').color;

          el.addEventListener('mouseenter', function () {
            el.setAttribute('color', data.color);
          });


          el.addEventListener('mouseleave', function () {
            el.setAttribute('color', defaultColor);
          });
        }
    });

// here, I create new circles that should later show the hover-behavior
      AFRAME.registerComponent('newcircle', {
        schema: {},
        multiple: true,
        init: function () {
            var sceneEl = document.querySelector('a-scene');
            var entityEl = document.createElement('a-ring');
            var posit = {x: 1, y: 0.1, z: -1};
            entityEl.setAttribute('position', posit);
            sceneEl.appendChild(entityEl);    
        }
      });

    </script>
  </head>

  <body>
    <a-scene background="color: #000000">
// here, the circle is created and should show the hover-behavior
      <a-entity newcircle change-color-on-hover></a-entity>          
    </a-scene>
  </body>
</html>

The circle is created and I expect it change color on hover, but it doesn't. Do you habe any idea why?

Thank you very much!


Solution

  • The mouseenter and mouseleave events are listened on the empty <a-entity> parent.

    If you add your component to the ring, then it should work as you want it to:

    // ...
    entityEl.setAttribute('position', posit);
    entityEl.setAttribute('change-color-on-hover', '')
    // ...
    

    Check it out in this fiddle.