Prevent the transmission of keydown events from dat.GUI to the Three.js scene to maintain event isolation

This code snippet (below) contains 2 event listeners:

renderer.domElement.addEventListener("pointerdown", changeColor, false);
document.addEventListener("keydown", changeColor, false);

Both of these event listeners trigger a color change in a cube. However, when editing the input parameter in the GUI, the 'keydown' events also cause a color change, which should be avoided.

The issue seems to arise from using document.addEventListener for the 'keydown' events. Changing it to

renderer.domElement.addEventListener
does not work.

How can I prevent 'keydown' events from triggering during GUI parameter edits?

Code

var renderer, controls, scene, camera;
var cube;

init();

function init() {

    // Scene
    scene = new THREE.Scene();
    scene.background = new THREE.Color(0xb0b0b0);

    // Camera
    camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.set(300, 300, 300);
    camera.up.set(0, 0, 1);

    // Light
    var ambientLight = new THREE.AmbientLight(0xcccccc, 0.2);
    scene.add(ambientLight);

    // Helpers
    var helpers = new THREE.Group();
    var grid = new THREE.GridHelper(200, 10);
    grid.rotation.x = Math.PI / 2;
    var axis = THREE.AxisHelper(100);
    helpers.add(grid);
    helpers.add(axis);
    scene.add(helpers);

    // Renderer
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    // Controls
    controls = new THREE.OrbitControls(camera, renderer.domElement);

    // Event listeners
    controls.addEventListener("change", render, false);

    // Draw the cube
    var cubeGeometry = new THREE.BoxGeometry(50, 50, 50);
        var cubeMaterial = new THREE.MeshBasicMaterial({color: 0x000088});
        cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
    scene.add(cube);
    
    // GUI
    params = {
        size: 50,
    };
    var gui = new dat.GUI();
    gui.add(params, "size", 0.0, 100, 1);
    
    // Listeners
    renderer.domElement.addEventListener("pointerdown", changeColor, false);
    document.addEventListener("keydown", changeColor, false);

    // Render
    render();
}

function changeColor(event) {
    cube.material.color.set(Math.random() * 0xffffff);
    cube.material.needsUpdate = true;
    render();
}

function render() {
    renderer.render(scene, camera);
}

Answer №1

One way to handle keydown events is by checking the target element within the event handler. If the target is an input, you can choose to do nothing:

function changeColor(event) {
    // Skip key event when editing dat.GUI input values
    if (event.target.localName == "input") {
        return;
    }
    // [...]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing the issue with the setFromMatrix() function not updating the position correctly?

Recently, I encountered a problem while working with 3D objects. I've been saving my scene on the server to prevent the objects from disappearing when refreshing the webpage. However, I'm facing an issue where the objects within the scene keep re ...

Do we need to use the "new" keyword when using ObjectID in a MongoDB query

Recently, I was immersed in a Typescript web project that involved the use of MongoDB and ExpressJS. One particular task required me to utilize a MongoDB query to locate and delete a document using the HTTP DELETE method. However, during the process of exe ...

Disabling the "Master Detail" feature in MUI

Exploring the functionality of MUI's Master Detail feature raised a question about CSV exporting from a Data Grid. When trying to export to CSV with the Master Detail implementation, the export functionality seemed to break (as expected). It technical ...

Exploring the functionalities of JavaScript methods and nested components within Vue.js

Learning Vue.js has been an interesting experience for me. However, I am facing challenges with methods and child elements in the library. It seems like there is something simple that I am overlooking. In my current project, I have list items rendered on ...

The "Splash Screen Div" page displayed during transitions and page loading

Creating a "Splash Screen Div" for a loading page involves waiting until everything is loaded and then hiding or moving the div off screen. Below is an example: index.html <div id="loading-Div"> <div id="bear-Logo"> < ...

jQuery dynamically updating calculations on a single row consecutively

Currently, I am in the process of developing a small table to calculate potential winnings from betting on a rubber duck race with specific odds for each duck. I have managed to get most of it working but have encountered an issue... Upon loading the pag ...

Trouble accessing nested components in Angular CLI beyond the first level of components

I'm diving into Angular CLI for the first time and trying to recreate a previous web project of mine. I've managed to nest and display components inside the root component successfully, but after that, I'm facing issues referencing any compo ...

Looking for a Regex pattern for this example: 12345678/90 MM/DD/YYYY

I am having success with the first 10 digits spaced apart, but unfortunately my date regex is not working as expected. ^(\d{6}\s{2}|\d{8})\/(\d{1}\s|\d{2})\s\/(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))&bso ...

Using Angular.js, apply the "visible" class conditionally based on a variable

My Cordova application is built with angular.js and consists of the following 2 files: app.html <div ng-controller="MyAppCtrl as myApp" ng-class="myApp.isWindows() ? 'windows' : ''"> and app.controller MyAppCtrl.$inject = [&ap ...

The Node application seems to be encountering an issue when attempting to handle

Whenever I click a button on my page in Node using Express, my JavaScript file sends the following request: toggleCartItem = index => { http = new XMLHttpRequest(); http.open("POST", `/cart_item/${index}`, true); http.send(); } Th ...

ways to dynamically retrieve input values in PHP

Is there a way to dynamically add and remove data fields, as well as increase and decrease fields dynamically in PHP? I am looking to retrieve the subject value in an array or JSON format using PHP only. https://i.stack.imgur.com/HqDCz.png <div data-ro ...

Update the displayed number on the input field as a German-formatted value whenever there is a change in the input, all while maintaining

In German decimal numbers, a decimal comma is used. When formatting, periods are also used for grouping digits. For example, the number 10000.45 would be formatted as 10.000,45. I am looking to create an input field (numeric or text) where users can input ...

What is the correct location to define the "env" setting in the eslint.config.js file?

In 2022, ESLint rolled out a new configuration system called the "flat config" here. Check out the documentation for the new "flat config". | Old configuration system documentation here. The "flat config" documentation shows that the `eslint.config.js` ...

Tips for adjusting the position of nodes that are overlapping in React Flow

Whenever node1 is moved over node2 in react-flow, they end up overlapping. I am looking to shift node2 towards the right to avoid this overlap. The desired outcome is for node2 to be shifted to the right side. ...

The attention remains fixed at the top of the page

I have implemented an update panel along with pagination links using a repeater control at the bottom of my page. However, I am encountering an issue where clicking on the pagination links does not bring the page to the top. I attempted to use the followin ...

Steps for aligning the upper rectangular text in the center of the larger rectangular border

https://i.stack.imgur.com/7yr5V.png I was aware of a particular element in html that had text positioned in the upper left corner, but my knowledge didn't go beyond that. Should I be adjusting the translation on both the X and Y axes based on the par ...

Utilizing a router to control a GET request for accessing an image file

Currently utilizing node.js in conjunction with the express framework, I am attempting to initiate a get request for an image by appending it to the body through $('body').append('<img src="images/image.gif?34567">'). Despite rece ...

JavaScript and CSS animations out of sync in terms of timing

I've been encountering some issues. I have an array containing 5 lines of text that change with a timer, but it seems that the css timer animation might not be synced properly or my @keyframes slidesdown setup could be incorrect. The delay between te ...

Having trouble with Django REST API and Axios POST request not functioning properly

I'm currently working on developing a simple API that allows users to input data, submit it, and have it stored in a database. To accomplish this, I am utilizing React and Django Rest Framework. In my App.js file: const [name, setName] = useState(&ap ...

The Angular datepicker is failing to trigger the ng-change event

I've run into a snag with the datepicker and ng-change functionality. Oddly enough, the ng-change event isn't triggering when I manually select a date by clicking on it, but it works fine when I input a date manually. Take a look at my code snip ...