How to retrieve the value of a variable from one JavaScript function and pass it to another

As a JavaScript beginner, I am looking for help in retrieving values from one function to another. Specifically, I would like to access the values of dinoRight, dinoLeft, and others in the cactus1move function.

const spawn = () => {
    const dinoRight = document.getElementById('dino').getBoundingClientRect().left + document.getElementById('dino').getBoundingClientRect().width;
    const dinoLeft = document.getElementById('dino').getBoundingClientRect().left; 
    const dinoHeight = document.getElementById('dino').getBoundingClientRect().height;
    const cactusTop = document.getElementById('cactus').getBoundingClientRect().top;
    const cactusWidth = document.getElementById('cactus').getBoundingClientRect().width;
    const containerLeft = document.getElementById('Container').getBoundingClientRect().left;
    cactus1move();
}
const cactus1move = setInterval(() => {
    if (cactusTop <= dinoBottom && dinoRight >= cactusLeft && cactusRight >= dinoLeft) {
        ...
    } else if (cactusLeft <= containerLeft + 10 && cactusLeft >= containerLeft){
        ...
    } else {
        ...
    }
}, 20)

Answer №1

function initialize() {
    const dinoRight = document.getElementById('dino').getBoundingClientRect().left + document.getElementById('dino').getBoundingClientRect().width;
    const dinoLeft = document.getElementById('dino').getBoundingClientRect().left; 
    const dinoHeight = document.getElementById('dino').getBoundingClientRect().height;
    const cactusTop = document.getElementById('cactus').getBoundingClientRect().top;
    const cactusWidth = document.getElementById('cactus').getBoundingClientRect().width;
    const containerLeft = document.getElementById('Container').getBoundingClientRect().left;
    moveCactus1(dinoRight, dinoLeft);
}


//not sure if you can pass it directly to the interval
const moveCactus1 = setInterval((dino_right, dino_left) => {
    if (cactusTop <= dinoBottom && dinoRight >= cactusLeft && cactusRight >= dinoLeft) {
        // Actions to take if conditions are met
    } else if (cactusLeft <= containerLeft+10 && cactusLeft >= containerLeft){
        // Actions to take if conditions are met
    } else {
        // Actions to take if conditions are not met
    }
}, 20);


//if it does not work you can pass the parameters to a function and then down to the interval
const moveCactus2 = (dino_right, dino_left) => {
    setInterval((dino_right, dino_left) => {
        if (cactusTop <= dinoBottom && dinoRight >= cactusLeft && cactusRight >= dinoLeft) {
            // Actions to take if conditions are met
        } else if (cactusLeft <= containerLeft+10 && cactusLeft >= containerLeft){
            // Actions to take if conditions are met
        } else {
            // Actions to take if conditions are not met
        }
    }, 20);
}

Answer №2

When writing your code, make sure to consider the scope of variables by declaring them appropriately. Variables declared inside functions are only accessible within that function, limiting their usefulness. To ensure both functions can access the variables, declare them outside the functions as shown below:

let dinoRight, dinoLeft, dinoHeight, cactusTop, cactusWidth, containerLeft;
const spawn = () => {
    dinoRight = document.getElementById('dino').getBoundingClientRect().left + document.getElementById('dino').getBoundingClientRect().width;
    dinoLeft = document.getElementById('dino').getBoundingClientRect().left; 
    dinoHeight = document.getElementById('dino').getBoundingClientRect().height;
    cactusTop = document.getElementById('cactus').getBoundingClientRect().top;
    cactusWidth = document.getElementById('cactus').getBoundingClientRect().width;
    containerLeft = document.getElementById('Container').getBoundingClientRect().left;
    cactus1move();
}
const cactus1move = setInterval(() => {
    if (cactusTop <= dinoBottom && dinoRight >= cactusLeft && cactusRight >= dinoLeft) {
        ...
    } else if (cactusLeft <= containerLeft + 10 && cactusLeft >= containerLeft){
        ...
    } else {
        ...
    }
}, 20)

Answer №3

It's best practice to pass parameters when calling a method instead of relying on global variables. This ensures that the method can be used independently and avoids unnecessary dependencies.

Below, I demonstrate calling the cactus1move method with the necessary values wrapped in an object. Inside the cactus1move function, I use destructuring assignment to extract the values from the object for further processing.

const spawn = () => {
  const dinoRight = document.getElementById('dino').getBoundingClientRect().left + document.getElementById('dino').getBoundingClientRect().width;
  const dinoLeft = document.getElementById('dino').getBoundingClientRect().left;
  const dinoHeight = document.getElementById('dino').getBoundingClientRect().height;
  const cactusTop = document.getElementById('cactus').getBoundingClientRect().top;
  const cactusWidth = document.getElementById('cactus').getBoundingClientRect().width;
  const containerLeft = document.getElementById('Container').getBoundingClientRect().left;
  cactus1move({
    dinoRight,
    dinoLeft,
    dinoHeight,
    cactusTop,
    cactusWidth,
    containerLeft
  });
}

const cactus1move = (data) => {
  return setInterval(() => {
    const {
      dinoRight,
      dinoLeft,
      dinoHeight,
      cactusTop,
      cactusWidth,
      containerLeft
    } = data;
    console.log('dinoRight', dinoRight);
    console.log('dinoLeft', dinoLeft);
    console.log('dinoHeight', dinoHeight);
    console.log('cactusTop', cactusTop);
    console.log('cactusWidth', cactusWidth);
    console.log('containerLeft', containerLeft);
  }, 2000);
}
#dino {
  width: 80px;
  height: 80px;
  background-color: #FFBB73;
  float: left;
}

#cactus {
  width: 90px;
  height: 90px;
  background-color: #FFBB33;
  float: left;
}

#Container {
  width: 100px;
  height: 100px;
  background-color: #FFBB13;
  float: left;
}
<div id='dino'></div>
<div id='cactus'></div>
<div id='Container'></div>
<button onclick="spawn()">spawn</button>

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

Issue with plotted point labels failing to display correctly on X Range Chart for the initial date of each month - Highcharts

Currently, I am implementing a chart that displays the timeline of activities using an x range. However, I have encountered an issue with the popup displaying data information when hovering over the bars. The problem arises specifically on the first date ...

When additional lines are drawn elsewhere on the HTML5 Canvas, the diagonal lines will gradually appear thicker and more pronounced

For horizontal and vertical lines, using a translation of 0.5 for odd stroke widths results in crisper and sharper lines. But what about diagonal lines? Link to jsfiddle <!DOCTYPE html> <html lang="en"> <body style="background: black"& ...

Tips for determining the width of an image and utilizing that measurement as the height in order to create a balanced square image

I am currently facing an issue with my code that is used to retrieve the width of an image which is set in percentages. Although I am able to obtain the width in pixels, I am struggling with correctly inserting the variable into the CSS property value usin ...

Switch to using addresses instead of latitude and longitude coordinates when utilizing the Google Maps API

I am looking to utilize Google Map Markers to indicate the locations where our services are offered. The code I have created using latitude and longitude is functioning properly, however, for my project I need to display city names instead of lat/long ...

Encountering issues with posting data on a straightforward Node.js form using routes

I'm having trouble getting a simple form to post within my NodeJS/ExpressJS app. The code in my app.js file (referred to as server.js) is as follows: var express = require('express'); var fs = require('fs'); var path = require(&a ...

Converting text data into JSON format using JavaScript

When working with my application, I am loading text data from a text file: The contents of this txt file are as follows: console.log(myData): ### Comment 1 ## Comment two dataone=1 datatwo=2 ## Comment N dataThree=3 I am looking to convert this data to ...

What steps do I need to take to deploy my React app onto a server?

I recently completed creating my first website with React and now I want to upload it to my server (HostGator). Can anyone guide me on how to do that? Thank you. ...

Saving the accurate x and y coordinates into the database

My website features draggable images that each have their own x and y positions. I am attempting to pass these values into a MySQL database, but I'm facing an issue where all the images are getting assigned the same x and y values in the database. In ...

TypeScript creates a .d.ts file that contains declaration statements rather than export declarations

When compiling my code using the command tsc --p typescript/tsconfig.json --outFile "dist/umd/index.d.ts", I encountered an issue. The contents of my tsconfig.json file are as follows: { "include": ["../src/**/*"], "exclude": ["../**/*.test.ts"], ...

Can html-webpack-plugin be configured to create <style> elements from CSS files?

I am managing a static site with Vue and Webpack. In my project, I have a file named style.css containing global CSS rules which I import using import './styles.css' in my index.js file. Additionally, I have some .vue files that generate their o ...

"Troubleshooting a Node.js JWT issue in a React.js

I've been diving into backend development and recently created some small APIs. They all function perfectly in Postman, but I encountered an issue when attempting to execute this particular call const onSubmit = async () => { try { setIsL ...

The module 'SharedModule' has imported an unexpected value of 'undefined'

When working with an Angular application, I want to be able to use the same component multiple times. The component that needs to be reused is called DynamicFormBuilderComponent, which is part of the DynamicFormModule. Since the application follows a lib ...

Newbie's Guide - Building React/React-Bootstrap JavaScript Components Post Linking CDNs in index.html

Exploring Glitch hosting for a React/React-Bootstrap website as part of my web development training. Although these tools are new to me, I have years of experience as a developer. Successfully linked React, React-Dom, Babel, and React-Bootstrap CDN's ...

Utilizing JQuery's .Toggle function in conjunction with a stylish CSS transform button

I am trying to create a toggle menu that shows and hides itself without requiring the button to be clicked twice. I have added e.preventDefault(); which solves the issue, but now the button does not transform as intended. $(document).ready(function() { ...

SyntaxError in ExpressJS: Encountered an unexpected token "C"

I'm having trouble saving my string to a comma-separated array. When I attempt to use the JSON.parse method, I encounter an error while sending a post request and trying to save a record: SyntaxError: Unexpected token c at Object.parse (native) ...

A variable in Javascript storing data about jQuery DOM elements

Currently, I am using the slick slider for my development (http://kenwheeler.github.io/slick/) In JavaScript, there is an event that returns a variable called 'slick' When I print the variable using console.log, this is what I see: https://i.s ...

How can I implement a search box on my HTML website without relying on Google Custom Search?

Greetings to all! I am currently managing a website filled with HTML content. I am looking to incorporate a search box into the site. After researching on Google, most of the results point towards using Google Custom Search. However, I require a search box ...

Validation of forms - Must include one particular word from a given set

I am in the process of utilizing Javascript to validate an input field with the specific formatting requirements outlined below: "WORD1,WORD2" The input must contain a comma separating two words, without any spaces. The first word (WORD1) can be any word ...

Tips for revealing a link after the user clicks on the submit button

I am looking to set up a webpage that will display a hyperlink after the submit button is clicked. For example, 1) wedding 2) engagement 3) birthday All three items are checkbox buttons and there is a textbox to input the budget. After clicking the sub ...

Can data be presented in AngularJS without the use of scope variables?

I have a method: <span ng-init="getJobApplicantsList(jobId)">(number should be display here)</span> Is there a way to display the data without having to store it in a scope variable? I need to use this method in many places. This is my cont ...