Onclick is not working on CSS3DObject

Hi!

When I make a CSS3DObject as follows:

  element = document.createElement('div');
  element.innerHTML = 'Test';

  element.setAttribute('onclick', 'alert(1)');

  const object = new CSS3DObject(element);
  object.position.x = parseFloat(0);
  object.position.y = parseFloat(0);
  object.position.z = parseFloat(-150);
  object.lookAt(this.camera.position);

  this.scene.add(object);

Renderer:

this.renderer = new CSS3DRenderer();
this.renderer .setSize(window.innerWidth, window.innerHeight);
this.container.appendChild(this.renderer.domElement);

renderFrame = () => {
    this.renderer.render(this.scene, this.camera);

    window.requestAnimationFrame(this.renderFrame);
 }

Unfortunately the onclick event doesn’t seem to work. I can see the hotspot, css hover effects work as well just not the click events. Not when I register it as event nor if I add it as attribute. Any Ideas?

I use three/examples/jsm/controls/OrbitControls.js as OrbitControl to look around my scene.

instead of

element.setAttribute('onclick', 'alert(1)');

try

element.addEventListener('pointerdown', () => { alert(1) })

2 Likes

Yep, using pointer events should solve this issue. Live example: https://jsfiddle.net/9tng8dp0/2/

2 Likes

Thanks! Would never have thought of that, works like a charm! :slight_smile: