Avoid propagation of a `keydown` event when editing input parameters with dat.GUI

I have this Fiddle:

https://jsfiddle.net/Peque/yrk93o7L/

With 2 event listeners:

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

They both trigger a color change in the cube. However, when I edit the input parameter in the GUI, keydown events also result in a color change, and I would like to avoid that. I am guessing this is because I am using document.addEventListener. However, if I use renderer.domElement.addEventListener instead it wont work.

How can I avoid keydown events to propagate when editing GUI parameters?

I have tried with this and it works just fine, but not sure it is the right approach:

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

Any other (better) way to do this?

I think this approach is okay for your use case.

BTW: You don’t need to set cube.material.needsUpdate = true; if you just update the color.

1 Like

@Mugen87 Thanks! I’ll wait 24 hours before accepting in case someone wants to share a different approach. :blush:

I’m curious, where do you see a working solution?

event.target.localName will return body or canvas depending from what element was dispatched from.

Now if you share with us, why two event handlers are needed here, perhaps a solution can be offered.

@rrrr_rrrr Sorry, I probably did not explain myself well.

The issue is when editing the input parameter in the GUI (i.e.: when you use SUPR, or Backspace, or any number to fill the parameter value). Those keydown events get propagated to the 3D scene as well, instead of being stopped at the GUI.

The working solution is when those keydown events are constrained to the GUI.

The pointer event handler is probably not needed for this example. Was just to show the difference in the DOM element (renderer for the pointer and document for the keys). In case I was doing something wrong.

Hope this helps clarify the question. :blush:

OK, looks like you found the solution.
Good luck.