Cannot run JS functions within a Three.js template on Codepen

Hi folks!

With my limited knowledge of JS, I managed to get a Three.js project going on CodePen:

https://codepen.io/grzegorz-rogala/pen/bNGrQpg/47225edabff7f71f3de3876eff215f36

However, now when I try to write up a simple function or an event listener that would be called by a button element outside of the canvas element, I get reference errors: ‘cannot find variable’ (and function name is given as variable name) or ‘not enough arguments’.

Where could I include non-three.js related code? I tried inside and outside three.js code template as well as inside the html body between the script tags and Codepen is giving me the same errors.

Thanks for your help!

This is a problem of editors, and a matter of JS itself, specifically scope.

Note, that this issue occurs, for example, in environments/editors such as Stack Overflow or CodeSandbox. The code will be wrapped in modules and you may encounter similar let say limitations. In this case, the functions will not be globally available. For example, if you write code locally in Visual Studio Code and include your script in the traditional way (without type="module") using a regular <script> tag, then all code goes into the global scope, and you will not get this type of errors

Try

<button id="btnNew">Rotate Model</button>

and put after tick function:

document.getElementById("btnNew").addEventListener("click", () => {
  if (model1) {
    model1.rotation.y += Math.PI / 2;
  }
});
1 Like

That worked like a charm and thanks for the detailed explanation!

1 Like