What is the best way to access a variable from one JavaScript file in a different file?

Currently, I have a simple cube scene set up in Three.js

Now, my goal is to add camera movement using perlin noise. To achieve this, I found and incorporated the Perlin noise library into my project:

https://github.com/josephg/noisejs

I then included the necessary script tags in the HTML file:

<script src="three.min.js"></script>  
<script src="my-three.js"></script>  
<script src="perlin.js"></script> 

In order to utilize the noise function, I created a variable within the perlin.js file:

var ruido = noise.simplex3(10, 10, 1);

The final step was to apply this variable to the camera. In my "my-three.js" file, I added the following line:

camera.position.z = ruido;

However, upon testing, I encountered an error:

Uncaught ReferenceError: ruido is not defined

It seems like the variable is not being recognized in the "my-three.js" file.

The complete content of "my-three.js" is as follows:

  var scene = new THREE.Scene();
  var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);

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

  var geometry = new THREE.BoxGeometry(1, 1, 1);
  var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
  var cube = new THREE.Mesh(geometry, material);
  scene.add(cube);

  camera.position.z = ruido;

  var render = function() {
    requestAnimationFrame(render);

    cube.rotation.x += 0.001;
    cube.rotation.y += 0.001;

    renderer.render(scene, camera);
  };

  render();

Any assistance would be greatly appreciated.

Answer №1

It's important to make sure the perlin.js file is included before the my-three.js file in your code, as the my-three.js relies on functions provided by perlin.js.

<script src="perlin.js"></script>
<script src="my-three.js"></script>

Answer №2

One effective solution is to adopt the AMD (Asynchronous Module Definition) approach along with libraries that support it.

Explore more about AMD here

This method helps address issues related to variables, modules, dependencies, and more.

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

Getting the Angular component class reference within a triggered Highcharts selection event callback - what's the best approach?

It seems like I'm facing a common javascript closure issue, but let me illustrate it with a specific example as I'm struggling to grasp it in an Angular context. In my Angular component, I'm using the Highcharts library to visualize data. W ...

How to trigger a JavaScript function when the UI-Router state is switched?

Within my Angular App, I am utilizing ui-router to manage navigation and other tasks. In a separate script file, there is a function that looks like this: $(function () { function doSomething(){ if ($('.thisclass').length) { $(' ...

Encountering a proxy error while attempting to create an account or log in, with no network

Embarking on my first web development journey, I utilized React-Redux to craft a React.js application within the client folder. For the backend code, I employed Node.js and MongoDb as my database. This project represents a significant milestone in my lear ...

Tips on retrieving the ul list value dynamically using jQuery when it changes

I have a list of countries with their dial codes and country codes. I need to find out which country is currently selected and retrieve its data-country-code using jQuery. Can anyone provide guidance on how to accomplish this? <ul class="country-list ...

Unlock the navigation tab content and smoothly glide through it in Bootstrap 4

Hey there, I have managed to create two functions that work as intended. While I have some understanding of programming, I lack a background in JavaScript or jQuery. The first function opens a specific tab in the navigation: <script> function homeTa ...

Is there a way to determine the top center of a rotated Cylinder in THREE.js?

Just starting out with WebGL and Three.js, I managed to create a cylinder with the original point at the bottom center. Here's the code snippet: var cylinderGeometry = new THREE.CylinderGeometry( topRadius, botRadius, randomCyliderHeight); cylinderG ...

What's the best way to group rows in an angular mat-table?

I am working on a detailed mat-table with expanded rows and trying to group the rows based on Execution Date. While looking at this Stackblitz example where the data is grouped alphabetically, I am struggling to understand where to place the group header c ...

Calculate the cumulative values in ng-repeat using AngularJS

I used ng-repeat to iterate through a JSON array. I calculated the number of nights by utilizing the dayDiff() function. Now, I need to find the total number of nights for all invoices. My project is built with AngularJS. Is there a way to retrieve the to ...

Having trouble retrieving accurate text information from a JavaScript link

I am encountering an issue with my code which consists of links with divs inside them. When I click on a link, it should display another div with data for "Case No" and "Type". However, the problem is that it only fetches the data from the first link click ...

Show the button's value in the textbox and update the selected button's color using JavaScript

I am having difficulty changing the background color of a selected button after displaying its value in a textbox. The code below successfully displays the button value in the textbox, but I can't figure out how to change the background color of the s ...

What is the best method for validating multiple fields in a form with Javascript?

I am currently working on validating multiple fields within a form. Although I lack experience in JavaScript, I have managed to piece together a code that is functional for the most part. If all fields are left blank, error messages prompt correctly. Howe ...

Firebase web authentication is most effective upon the second attempt

I am currently working on a website that interacts with Google's firebase to read and write data. The website has both anonymous and email authentication enabled. Users can view the data anonymously, but in order to edit or write new data, they must s ...

The chart appears oversized in the vue js. How can I make it smaller in size?

I recently integrated a line chart from Chart JS into my Vue.js project, but the chart is taking up too much space on my webpage. I'm looking for ways to make it appear smaller and more compact. This is my first time working with charts in Vue.js, so ...

Utilize a jQuery plugin within an AngularJS function

I am using the jQuery plugin select2 and I need to call the select2 function in AngularJS. Although I am aware that I can utilize angular-ui/ui-select, the page design specifically requires the jQuery plugin select2. My goal is to update the value in the ...

Using AJAX to dynamically load content from a Wordpress website

Currently, I have been experimenting with an AJAX tutorial in an attempt to dynamically load my WordPress post content onto the homepage of my website without triggering a full page reload. However, for some reason, when clicking on the links, instead of ...

D3 circle packing showcases a concise two-line label text

I've browsed through the topics on this site, but none of the solutions provided worked for my issue. Is there a way to display text in two lines for long texts in D3 circle packing? The following code is what I am using to show labels on circles: c ...

What could be causing the error when trying to submit to OData Edm.Decimal type?

Having an issue submitting JSON to an OData service. The $metadata indicates it expects this format: <Property Name="curClaimValue" Type="Edm.Decimal" Nullable="true" Precision="19" Scale="4"/> This snippet is from my JSON data: ..."curClaimValue" ...

The button's status changes to disabled until I click outside the input field in Angular

I am currently facing an issue with a form (heat index calculator) that requires 2 inputs - a dropdown and a button. The button is disabled when there are no inputs or if the inputs are invalid. Everything works correctly, except for the fact that even whe ...

The Ajax/jQuery output is not showing up in the iframe, but is instead appearing on a separate page

I've scoured various forums and websites, attempting to troubleshoot the issue described below without success. This problem persists in both IE 11 and Firefox 10.0.2. My goal is to submit a form (POST) to a website () and showcase the resulting bri ...

A collection of asynchronous requests stemming from a sole request

I am facing a unique ajax scenario that is proving to be quite challenging for me. Here is the specific sequence of events that I need to coordinate: An initial request returns an array of ID numbers. A separate request needs to be sent for each ID in ...