CSS2DObject click event didn't work

if (intersects.length > 0) {
            let dot_count = $(".dot").length;
            let text_count = $(".textField").length;
            const numDiv = document.createElement('div');
            numDiv.className = 'dot';
            numDiv.id = `div_${dot_count}`;
            numDiv.textContent = `${dot_count + 1}`;
            numDiv.style.marginTop = '-1em';
            const earthMassLabel = new CSS2DObject(numDiv);
            earthMassLabel.position.set(intersects[0].point.x, intersects[0].point.y, 0.5);
            scene.add(earthMassLabel);

            const textField = document.createElement('textarea');
            textField.className = 'HotspotAnnotation';
            textField.id = `textField_${text_count}`
            //textField.style.top = `${mouse_position[1]}px`;
            //textField.style.left = `${mouse_position[0]}px`;
            const textFieldLabel = new CSS2DObject(textField);
            textFieldLabel.position.set(intersects[0].point.x, intersects[0].point.y, 0.5)
            scene.add(textFieldLabel);
            document.body.appendChild(numDiv);
            var bb = document.getElementsByClassName("dot");
            console.log('bb',bb);
            console.log('bb[0]',bb[0]);
            const bv = document.getElementById("div_"+dot_count);
            console.log('bv',bv);
            
            
            bv.addEventListener("click", () => { console.log("click"); });

        }
    });

I am performing click event on div element but it didn’t work where I am doing wrong?

Try it with pointerdown instead of click.

1 Like

I tried that also didn’t work, and one thing I wanna know I am adding textarea in threejs scene it is not editable any reason behind that?

Please demonstrate the issue with a small live example.


In the above image I am adding textarea it is not editable below is the code

if (intersects.length > 0) {
            let dot_count = $(".dot").length;
            let text_count = $(".textField").length;
          
            const numDiv = document.createElement('div');
            numDiv.className = 'dot';
            numDiv.id = `div_${dot_count}`;
            numDiv.textContent = `${dot_count + 1}`;
            numDiv.style.marginTop = '-1em';
            const earthMassLabel = new CSS2DObject(numDiv);
            earthMassLabel.position.set(intersects[0].point.x, intersects[0].point.y, 0.5);
            scene.add(earthMassLabel);

            const textField = document.createElement('textarea');
            textField.className = 'textField';
            textField.id = `textField_${text_count}`
            textField.style.top = `${mouse_position[1]}px`;
            textField.style.left = `${mouse_position[0]}px`;
            const textFieldLabel = new CSS2DObject(textField);
            textFieldLabel.position.set(intersects[0].point.x, intersects[0].point.y, 0.5)
            scene.add(textFieldLabel);
            document.body.appendChild(numDiv);
            //document.body.appendChild(textField)
            document.getElementById("div_" + dot_count).addEventListener('click', function () {
                console.log("div " + dot_count + "selected");
                if(document.getElementById('textField_'+text_count).style.display !== "none"){
                    document.getElementById('textField_'+text_count).style.display = "none";
                }else{
                    document.getElementById('textField_'+text_count).style.display = "block";
                }

            });
            const a =<HTMLInputElement> document.getElementById("testing");
            a.addEventListener('input',function(e){
                console.log((e.target as HTMLInputElement).value);
                textField.innerHTML = (e.target as HTMLInputElement).value;
            })
        }
    });

This is not a live example!

Be aware that you have been warned for making too many low effort posts in this forum. Please keep this in mind and invest more time in your posts.

It’s best to demonstrate issues with small and compact live examples.

Maybe some element is above of labels stop click. And need set z-index top

sir I can’t post whole code due to company policies that’s why I am sharing snippets here, understand my situation…

I tried that still didn’t work it is only resizing not editable

The idea is not to share the entire code. The idea is to demonstrate the issue with a small example.

one more thing I wanna know like I am placing label 1 in scene it is working perfect where I am clicking mouse but when I am placing textarea with that it goes far from that I am passing same coordinates to both where is the issue in that?

ok sir, next time I will keep in my mind, and thanks

To answer your original question: Check out how the following live example sets an event listener to the “earth” label: Edit fiddle - JSFiddle - Code Playground

Thanks sir, any reference related to how we can add textarea three js which is editable, we can type in it and add some text

Editable and can type. Maybe bad browser.
image

Share your code pls with css and html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<title>three.js css2d - label</title>
		<link type="text/css" rel="stylesheet" href="main.css">
		<style>
			.label {
				color: #FFF;
				font-family: sans-serif;
				padding: 2px;
				background: rgba( 0, 0, 0, .6 );
			}
		</style>
	</head>
	<body>
		<div id="info"><a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> css2d - label</div>

		<!-- Import maps polyfill -->
		<!-- Remove this when import maps will be widely supported -->
		<script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>

		<script type="importmap">
			{
				"imports": {
					"three": "../build/three.module.js"
				}
			}
		</script>

		<script type="module">

			import * as THREE from 'three';

			import { OrbitControls } from './jsm/controls/OrbitControls.js';
			import { CSS2DRenderer, CSS2DObject } from './jsm/renderers/CSS2DRenderer.js';

			import { GUI } from './jsm/libs/lil-gui.module.min.js';

			let gui;

			let camera, scene, renderer, labelRenderer;

			const layers = {

				'Toggle Name': function () {

					camera.layers.toggle( 0 );

				},
				'Toggle Mass': function () {

					camera.layers.toggle( 1 );

				},
				'Enable All': function () {

					camera.layers.enableAll();

				},

				'Disable All': function () {

					camera.layers.disableAll();

				}

			}

			const clock = new THREE.Clock();
			const textureLoader = new THREE.TextureLoader();

			let moon;

			init();
			animate();

			function init() {

				const EARTH_RADIUS = 1;
				const MOON_RADIUS = 0.27;

				camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 200 );
				camera.position.set( 10, 5, 20 );
				camera.layers.enableAll();
				camera.layers.toggle( 1 );

				scene = new THREE.Scene();

				const dirLight = new THREE.DirectionalLight( 0xffffff );
				dirLight.position.set( 0, 0, 1 );
				dirLight.layers.enableAll();
				scene.add( dirLight );

				const axesHelper = new THREE.AxesHelper( 5 );
				axesHelper.layers.enableAll();
				scene.add( axesHelper );

				//

				const earthGeometry = new THREE.SphereGeometry( EARTH_RADIUS, 16, 16 );
				const earthMaterial = new THREE.MeshPhongMaterial( {
					specular: 0x333333,
					shininess: 5,
					map: textureLoader.load( 'textures/planets/earth_atmos_2048.jpg' ),
					specularMap: textureLoader.load( 'textures/planets/earth_specular_2048.jpg' ),
					normalMap: textureLoader.load( 'textures/planets/earth_normal_2048.jpg' ),
					normalScale: new THREE.Vector2( 0.85, 0.85 )
				} );
				const earth = new THREE.Mesh( earthGeometry, earthMaterial );
				scene.add( earth );

				const moonGeometry = new THREE.SphereGeometry( MOON_RADIUS, 16, 16 );
				const moonMaterial = new THREE.MeshPhongMaterial( {
					shininess: 5,
					map: textureLoader.load( 'textures/planets/moon_1024.jpg' )
				} );
				moon = new THREE.Mesh( moonGeometry, moonMaterial );
				scene.add( moon );

				//

				earth.layers.enableAll();
				moon.layers.enableAll();

// YOUR CODE HERE

const textField = document.createElement('textarea');
textField.className = 'textField';
textField.id ="bbb";
textField.style.top = "100px";
textField.style.left = "200px";
const textFieldLabel = new CSS2DObject(textField);
textFieldLabel.position.set(0,0, 0.5)
scene.add(textFieldLabel);

//

				const earthDiv = document.createElement( 'div' );
				earthDiv.className = 'label';
				earthDiv.textContent = 'Earth';
				earthDiv.style.marginTop = '-1em';
				const earthLabel = new CSS2DObject( earthDiv );
				earthLabel.position.set( 0, EARTH_RADIUS, 0 );
				earth.add( earthLabel );
				earthLabel.layers.set( 0 );

				const earthMassDiv = document.createElement( 'div' );
				earthMassDiv.className = 'label';
				earthMassDiv.textContent = '5.97237e24 kg';
				earthMassDiv.style.marginTop = '-1em';
				const earthMassLabel = new CSS2DObject( earthMassDiv );
				earthMassLabel.position.set( 0, - 2 * EARTH_RADIUS, 0 );
				earth.add( earthMassLabel );
				earthMassLabel.layers.set( 1 );

				const moonDiv = document.createElement( 'div' );
				moonDiv.className = 'label';
				moonDiv.textContent = 'Moon';
				moonDiv.style.marginTop = '-1em';
				const moonLabel = new CSS2DObject( moonDiv );
				moonLabel.position.set( 0, MOON_RADIUS, 0 );
				moon.add( moonLabel );
				moonLabel.layers.set( 0 );

				const moonMassDiv = document.createElement( 'div' );
				moonMassDiv.className = 'label';
				moonMassDiv.textContent = '7.342e22 kg';
				moonMassDiv.style.marginTop = '-1em';
				const moonMassLabel = new CSS2DObject( moonMassDiv );
				moonMassLabel.position.set( 0, - 2 * MOON_RADIUS, 0 );
				moon.add( moonMassLabel );
				moonMassLabel.layers.set( 1 );

				//

				renderer = new THREE.WebGLRenderer();
				renderer.setPixelRatio( window.devicePixelRatio );
				renderer.setSize( window.innerWidth, window.innerHeight );
				document.body.appendChild( renderer.domElement );

				labelRenderer = new CSS2DRenderer();
				labelRenderer.setSize( window.innerWidth, window.innerHeight );
				labelRenderer.domElement.style.position = 'absolute';
				labelRenderer.domElement.style.top = '0px';
				document.body.appendChild( labelRenderer.domElement );

				const controls = new OrbitControls( camera, labelRenderer.domElement );
				controls.minDistance = 5;
				controls.maxDistance = 100;

				//

				window.addEventListener( 'resize', onWindowResize );

				initGui();

			}

			function onWindowResize() {

				camera.aspect = window.innerWidth / window.innerHeight;

				camera.updateProjectionMatrix();

				renderer.setSize( window.innerWidth, window.innerHeight );

				labelRenderer.setSize( window.innerWidth, window.innerHeight );

			}


			function animate() {

				requestAnimationFrame( animate );

				const elapsed = clock.getElapsedTime();

				moon.position.set( Math.sin( elapsed ) * 5, 0, Math.cos( elapsed ) * 5 );

				renderer.render( scene, camera );
				labelRenderer.render( scene, camera );

			}

			//

			function initGui() {

				gui = new GUI();

				gui.add( layers, 'Toggle Name' );
				gui.add( layers, 'Toggle Mass' );
				gui.add( layers, 'Enable All' );
				gui.add( layers, 'Disable All' );

			}

		</script>
	</body>
</html>

Thanks a lot

1 Like