Update the outer function variable using the inner function variable in JavaScript

I've been diving into JavaScript for a new project and I could really use some guidance.

My current hurdle involves updating the outer variables xPosition and yPosition with the new positions generated by the getMousePosition() function within the positionManager() function, but unfortunately it's not working as expected.

After scouring various online resources (including this platform), it seems like the issue may be related to closures, scopes, and local variables, which still leave me a bit perplexed.


Edit1: Apologies for any confusion. What I meant was that the value of var xPosition = 0; isn't being replaced by the values from the positionManager() function. The goal was for xPosition = mousePos.x to take over, but it doesn't seem to be happening.

Edit2: Every time the mouse moves on the canvas, the getMousePosition function captures the mouse coordinates. Subsequently, the positionManager should update the topmost var xPosition. However, despite these actions, the var xPosition continues to display 0.

function mouseController(canvas, context) {

    var xPosition = 0; // To be updated by values from positionManager.
    var yPosition = 0; // ^

    canvas.addEventListener("mousemove", positionManager);
    canvas.addEventListener("mouseout", hideCoordinates);
    canvas.addEventListener("click", drawWidget);

    /**
     *Gets the mouse position.
     * @param canvas
     * @returns x and y coordinates. Use (VARIABLE NAME).x and (VARIABLE NAME).y
     */
    function getMousePosition(canvas, event) {
        var rect = canvas.getBoundingClientRect();

        return {
            x: Math.round((event.clientX-rect.left)/(rect.right-rect.left)*canvas.width),
            y: Math.round((event.clientY-rect.top)/(rect.bottom-rect.top)*canvas.height)
        };
    }

    /**
     * Manages and directs the mouse positions received from getMousePosition().
     * 
     * @param event 
     */
    function positionManager(event) {
        var mousePos = getMousePosition(canvas, event);
        // Formats a message that shows the coordinates.
        var mouseCoordinates = 'Coordinates: ' + mousePos.x + ',' + mousePos.y;

        xPosition = mousePos.x; // Update the global variable with this new value.
        yPosition = mousePos.y;
        console.log("positionManager xPosition: " + xPosition); // Operates correctly, showing new coordinates each time the mouse moves.

        // Sends the message to be displayed.
        displayCoordinates(mouseCoordinates);
    }
    console.log("global var xPosition: " + xPosition); // Still showing 0 even after positionManager
}   

Answer №1

An Event Listener has been implemented for the "mousemove" event triggering the positionManager method. It's important to note that this method will only run if the "mousemove" event takes place.

Once the mouseController method is called, the "mousemove" event must finish before the method finishes executing.

This indicates that the program flow will move on to the next line, which includes the

canvas.addEventListener("mouseout",..)
, and eventually reach the final line with the console.log(...) statement without running the positionManager function.

The sequence of execution looks like this:

var yPosition = 0;

canvas.addEventListener("mousemove", positionManager);
canvas.addEventListener("mouseout", hideCoordinates);
canvas.addEventListener("click", drawWidget);
// The program then jumps to the last line displayed below.
console.log("global var xPosition: " + xPosition);

It would be advisable to verify the values of the variables xPosition and yPosition once the "mousemove" event happens.

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

How can I redirect to the newly saved MongoDB ID after an Express POST request?

After saving a new document to my mongo database with a POST request, is it possible to redirect to the exact document ID? I'm unsure of how to achieve this and have been unable to find any resources that provide a clear answer. Is it possible to imp ...

When making an Ajax call, the response is in JSON format when executed locally, but switches to

Whenever I send an ajax request and retrieve data, the response varies depending on where I execute the code. When I test the web page using Visual Studio and inspect the output in developer tools, I see JSON format like {"d":{"__type":"WebService+MyObject ...

The functionality of the OnClientClick event within the ASP.NET platform

While utilizing ASP.NET to pass a value to a JavaScript function, I encountered an issue where it doesn't seem to work when trying to pass a value from another control. It seems to behave as if there is a syntax error and just reverts back to the main ...

Validation of the form will occur both when it is submitted and when it loses

I have a function that validates my inputs on the focusout event. However, when I submit the form, I need the form to be validated again. How can I achieve this? If I attempt the following: $("#formcontato").submit(function(event){ event.preventD ...

Altering information with the use of history.pushState throughout time

I've created a template that I want to load using the jQuery .load() function. However, during testing, I discovered that it's not loading at all. Here is the code I'm trying to use for loading: function open() { history.p ...

Looking to leverage iframes in your Javascript code?

Currently, I am implementing a JSP popup window using JavaScript with an iframe to display a table of multiple records. However, when I disable the table of multiple records, it does not prevent the onclick function (hyperlink). The code snippet is provid ...

How can one create a hidden color box?

$.colorbox({ href:"/check.html", transition:"elastic", speed: 150, innerWidth:"910", iframe:true, fastIframe:false, fixedPosition:fixedPos, onComplete:function(){ var $ ...

I am encountering an issue with identifying a directory in Node.js

This is my HTML code <div id="done_work_1" class="logo-slide-track"> </div> <script>$.ajax({ url: "/static/home/done/", success: function (data) { $(data).find("a").attr("href&q ...

Error encountered while attempting to build Ionic 5 using the --prod flag: The property 'translate' does not exist on the specified type

I encountered an error while building my Ionic 5 project with the --prod flag. The error message I received is as follows: Error: src/app/pages/edit-profile/edit-profile.page.html(8,142): Property 'translate' does not exist on type 'EditProf ...

Determine the size of an array by utilizing the map function in ES6

Attempting to determine the length of an array using ES6 with the following code, but encountering issues. a=[[1,2,3,4],[4,5,6]] result = a.map(d=>({d[0]:d.length})) console.log(result) The correct method is: a=[[1,2,3,4],[4,5,6]] result = a.map(d=&g ...

Restrict the number of GET requests made using D3.js and the Twitter API

Currently, I have made adjustments to my D3.js chart by switching from mouseover/mouseout events to mousemove. While this change has caused several issues in the chart, the most significant one pertains to my GET statuses/show/:id requests. In the past, h ...

Modifying a leave transition in Vue.js dynamically following the completion of an enter transition

I am dealing with a dynamic transition for a slider element that moves left or right. Vue only allows me to have one transition, so I am using a dynamic transition property like this: <transition v-bind:name="'slider-' + slideDirection"> ...

changing the visible style of a div element using JavaScript

I'm having an issue with a link on my webpage that is supposed to show or hide a <div id="po" style="display:none;">some html</div> element. The first time I click the link, the div displays properly. However, after tha ...

Hiding a column in jQuery DataTables

Can the jquery datatables plugin be used to easily hide and show a table column? I've successfully refreshed the table data by using fnClearTable and fnAddData. However, I'm facing a challenge in one of my table views where I need to hide certa ...

Question about using React, NPM, Vite, Babel, and Node.js together

I want to confirm my understanding. So, if I decide to create a react 'app' and incorporate babel for jsx support. Then, I opt for vite for enhanced development runtime and packaging. Lastly, I utilize node.js to execute my code. To sum it up, ...

Basic Timer with Visual Background

Struggling to find the right CSS/script for a straightforward countdown timer, Here are the requirements: Countdown in days only, no need for hours, minutes, and seconds Ability to use a custom image as background I've scoured online searches but n ...

Maintain checkbox state through page reloads using ajax

Currently, I am troubleshooting a script that is intended to keep checkbox values checked even after the page is reloaded or refreshed. The code snippet below was implemented for this purpose, but unfortunately, it doesn't seem to be functioning corre ...

Tips for successfully passing an object with a list property in an ajax request

I have encountered a similar problem to This previous question, but I am struggling to implement the solutions provided. I am unsure of where to include the ModelBinder code mentioned in the responses, so I will explain my issue here. I am working with a s ...

Experience the power of live, real-time data-binding for date-time input with AngularFire in 3 different

Here is a simplified version of my code snippet: tr(ng-repeat='entry in ds3.entries | orderBy:orderByField:reverseSort | filter:query as results') td input.screen(type='datetime-local', ng-model='entry.date_recei ...

Oops! There was an issue with building the module in ./src/index.js using babel-loader

I'm running into issues setting up ReactJs from scratch. Whenever I try to use npm start, dev, build, or watch, I encounter the error shown below: ERROR in ./src/index.js Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError ...