JavaScript - the global and local variable dilemma

REVISED2: I'm encountering an issue with converting images to canvas using Pixastic in HTML5. How can I 'return' this converted image back to a global variable? Any suggestions?

<img id="mainIllustration" alt="main illustration" src="Img/Model01.png">
Illust...o_03.js (line 24)
<canvas id="mainIllustration" class="" width="278" height="659" style="" title="" tabindex="-1">
Illust...o_03.js (line 32)
<img id="mainIllustration" alt="main illustration" src="Img/Model01.png">
Illust...o_03.js (line 24)
<canvas id="mainIllustration" class="" width="278" height="659" style="" title="" tabindex="-1">
Illust...o_03.js (line 32)
<img id="mainIllustration" alt="main illustration" src="Img/Model01.png">
Illust...o_03.js (line 24)
<canvas id="mainIllustration" class="" width="278" height="659" style="" title="" tabindex="-1">

REVISED 1: It seems that the issue lies with Pixastic manipulating the image and not returning it to the global image variable (eMainIllustration). Any advice on how to solve this problem?

UPDATED MESSAGE:

Hello everyone,

I am working with the Pixastic library and facing confusion regarding global and local variables.

Below are two sets of code, one where the variable is globally defined as desired and another where it is locally defined.

The first code snippet works fine with the locally defined variable eMainIllustration and the function functions properly.

    var eDisplayTableSlideState = false;
    function displayTableSlideIn()
    {
        var eMainIllustration = document.getElementById("mainIllustration"); // eMainIllustration is locally defined
        if (eDisplayTableSlideState === false)
        {
            $("#displayTable").animate ({top: "-=33px", left: "+=66px", width: "-=198px", height: "-=48px"}, 750, "swing",function()
            {
                Pixastic.process (eMainIllustration,"blurfast", {amount: 0.1});
                return (eDisplayTableSlideState = true);
            });
        } else
        {
            $("#displayTable").animate ({top: "+=33px", left: "-=66px", width: "+=198px", height: "+=48px"}, 500, "swing",function()
            {
                Pixastic.revert(eMainIllustration);
            });
            return (eDisplayTableSlideState = false);
        }
    }

However, when the variable eMainIllustration is set globally, the code within the 'else' part of the function does not work. Why is that?

// eMainIllustration is locally defined
var eMainIllustration = document.getElementById("mainIllustration");
    var eDisplayTableSlideState = false;
    function displayTableSlideIn()
    {
        if (eDisplayTableSlideState === false)
        {
            $("#displayTable").animate ({top: "-=33px", left: "+=66px", width: "-=198px", height: "-=48px"}, 750, "swing",function()
            {
                Pixastic.process (eMainIllustration,"blurfast", {amount: 0.1});
                return (eDisplayTableSlideState = true);
            });
        } else
        {
            $("#displayTable").animate ({top: "+=33px", left: "-=66px", width: "+=198px", height: "+=48px"}, 500, "swing",function()
            {
                Pixastic.revert(eMainIllustration);
            });
            return (eDisplayTableSlideState = false);
        }
    }

Could the issue be related to not returning the state of the changed eMainIllustration in the first half of the function? How can I resolve this?

Thank you,

Answer №1

Have you ever wondered what happens when you alert or console.log the variable "out" inside a function? I've had my fair share of struggles when it comes to defining global variables within functions.

My point is, sometimes the DOM might not be fully loaded yet. You can try using the following code snippet:

if(window.addEventListener) {
    window.addEventListener('DOMContentLoaded', function() {
        //The DOM is now ready. You can set your global variables' values here.
    });
} else {
    //If you're dealing with Internet Explorer, use the attachEvent method instead.
}

Answer №2

One possible reason for this issue is the positioning of your Javascript code on the page.

If your code is placed at the top of the page, there might be a delay in loading the mainIllustration dom element before the script is executed.

Moving the code just above the closing body tag ensures that the variable will be populated as the entire dom will be loaded when the Javascript runs.

Therefore, if the code works inside a function, it means the dom is fully loaded before calling the function; however, it may not work if placed outside a function.

var eMainIllustration = document.getElementById("mainIllustration");

Edit

<script type="text/javascript">
    $(document).ready(function() {
        load("path_to_javasript");
     });
</script>

Answer №3

After some careful consideration, I managed to solve the issue at hand.

For those who may be unsure about how Pixastic operates, allow me to share my insights and provide a solution to the problem I encountered.

The Pixastic blurfast (& blur) plugin's 'revert function' essentially restores the element to its original state. Essentially, it undoes all changes made by previous effects, reverting the element back to its original appearance without adding any new effects.

It is important to note that when applying a Pixastic effect, the image transitions into an HTML5 canvas element. When using the revert function, this transition is reversed, restoring the original 'image' in place of the canvas element.

The confusion around global and local variables was resolved by implementing 'return' at the end of the function. Interestingly, this aspect turned out not to be the root cause of the issue; rather, the problem lied in my incorrect attempt to implement the revert functionality.

I sincerely hope this explanation proves useful to someone facing a similar challenge.

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

I would like to check if a given username and password exist in my JSON data

Trying different methods but not achieving the desired outcome. I have limited knowledge about JSON, gathered some information from online sources. var loginDataList = [{ "username": "abc", "password": "abc123" }, { "username": "richa", "p ...

Determining the file path in HTML5

Can anyone help me with retrieving the file path using html5 javascript once a user selects a file? I require the file path for a specific scenario: In this case, the user uploads a file and pauses it (currently only supported by Mozilla browsers), then c ...

Sequentially loading Bootstrap columns as the page loads

Is there a way to load columns one by one with a time gap when the page is loaded? Here's the code snippet that can achieve this: setTimeout(function() { $("#box1").removeClass("noDisplay"); },1000); setTimeout(function() { ...

Updating a JSON data structure after removing an item using AngularJS

As a newcomer to AngularJS, I have created a Service using Java and integrated it into Angular to handle the deletion of Contact objects. On my homepage in AngularJS, this is the code I have: <!--RESULTS--> <form> <table class="table table ...

Choice of product variations as a package

I am currently working on a project and here is the data structure I have set up for options and combinations: Options: "options": [ { "id": "96ce60e9-b09b-4cf6-aeca-83f75af9ef4b", "position": 0, "name": & ...

eliminating list item from unordered list depending on the input of either first or last name

My objective is to refine a lengthy list as the user types in a search for a specific person by first or last name. The current code I have functions adequately, but encounters an issue when there is a space in the input field. My goal is to allow users to ...

What is the best way to create a layout with two images positioned in the center?

Is it possible to align the two pictures to the center of the page horizontally using only HTML and CSS? I've tried using this code but it doesn't seem to work: #product .container { display: flex; justify-content: space-between; flex-w ...

Using jQuery to fetch and display content from an external webpage

Is there a more effective method for loading an external web page on the same server? I've experimented with .load() and .get(), but they only load the page after the PHP script is finished. I've also used an iFrame, which displays the informatio ...

Can you explain the purpose of App.hiddenDivs in jQuery code snippet provided?

Exploring various JQuery performance tips on this insightful website Do you happen to know the significance of App.hiddenDivs ? ...

Attempting to load using ajax, Chrome and jquery-mobile will modify the location of the window through setting window.location.href

I'm encountering a challenge with my mobile application where I need to redirect users to the login page on a 401 ajax call. However, it seems that jQM is attempting to load this via AJAX when the request is sent. This solution works flawlessly for s ...

How can we prevent the continual overwriting of Object values?

I'm currently working on extracting data from the USDA Food Data Central API. Specifically, I'm interested in retrieving the "name" and "amount" values under the "nutrient" section. The excerpt below shows the information retrieved: Input- repor ...

AngularJS is incapable of detaching forms from objects

Creating forms dynamically using ng-repeat and adding them to the vm.forms object is causing issues. When an item is removed from the array, the corresponding form is deleted but the key in the vm.forms object remains, leading to undefined errors. angul ...

Transform Objects Array from AJAX Response into a Distinct JSON Entity

I am encountering a problem with a sample endpoint that is returning [object Object] for JSON data, and I can't figure out why. Mock API Initially, my code was a bit confusing, but fortunately, I found a clearer solution in another answer. functio ...

Problem with Vue JS Hooper Image Slider (integrated into NuxtJS application)

Issue with Loading Images I encountered a problem while using the carousel feature in this GitHub project (). The images in the carousel do not display on the first load; instead, a loader animation image appears. However, upon refreshing the page, the ca ...

Updating the background color using typescript

Before transitioning to angular development, I had experience working with vanilla Javascript. I encountered a challenge when trying to modify the css properties of specific elements using Typescript. Unfortunately, the traditional approach used in Javascr ...

kineticjs equivalent to jquery sortable

Could someone recommend a kineticjs plugin or script that works with jquery's "sortable" function? I am trying to create a list of shapes where I can drag and drop them, and when one element moves, the other elements shift into place. ...

Having trouble sending a POST request from my React frontend to the Node.js backend

My node.js portfolio page features a simple contact form that sends emails using the Sendgrid API. The details for the API request are stored in sendgridObj, which is then sent to my server at server.js via a POST request when the contact form is submitted ...

"An issue has been detected in the Entry module, which cannot be located in

My journey into JavaScript is just beginning, as I diligently follow a well-structured node tutorial available on Github. Despite my best efforts in all the modules, I keep encountering an error message whenever I run yarn dev:wds. ERROR in Entry modu ...

How to set default props in Vue Select component?

I have been utilizing the vue-multiselect plugin from this website: Given that I plan to use it frequently, I am interested in establishing some default props. For instance, my aim is to have the selectLabel prop set as an empty string and possibly con ...

A guide to extracting functions from a `v-for` loop in a table

Beginner here. I am attempting to create a dropdown menu for the div with an id matching my specific name. For instance, let's say my table column names are: A, B, C. I only want to have a dropdown menu for column A. The template of my table looks ...