It appears that the JavaScript global dynamic variable is undefined as it changes from function to function, suggesting it might be

I'm encountering an issue with the way these two functions interact when used in onclick calls of elements. Due to external circumstances beyond my control, I need to keep track of when and how elements are hidden.

Everything works perfectly as intended, except for one thing - the undefined check in the show function. I set a global variable when hiding elements and I aim to utilize it again when showing them. However, the problem arises when I discover that what I initially thought was a global variable turns out not to be so in the show function.

function branchShow(targetID, triggerID){
    var target = document.getElementById(targetID);
    var trigger = document.getElementById(triggerID);
    var parentID = trigger.parentElement.parentElement.parentElement.parentElement.id;
    var globalMemory = "wasIHiddenBefore_" + parentID

    if (typeof window[globalMemory] !== "undefined"){
        if (window[globalMemory]) {
            console.log(globalMemory + " is evaluated true");
            window[globalMemory] = false;
        } else {
            console.log(globalMemory + " is evaluated false");
            target.setAttribute("style","display: block;");
        }
    } else {
        console.log(globalMemory + " is undefined");
        target.setAttribute("style","display: block;");
    }
};

function branchHide(targetID, triggerID){
    if (typeof i !== "undefined" ) {var iMemory = i;}
    if (typeof j !== "undefined" ) {var jMemory = j;}
    if (typeof k !== "undefined" ) {var kMemory = k;}
    var target = document.getElementById(targetID);
    target.setAttribute("style","display: none;");

    //don't want to flag on load
    if (hasLoadFinished){
        window["wasIHiddenBefore_" + targetID] == true;
        console.log("wasIHiddenBefore_" + targetID + " created as true");
    }
    .
    .
    .

The output from the console during a test run can be seen below. The 4th and 6th lines are particularly crucial in highlighting the problem at hand.

wasIHiddenBefore_1e16f2513f7842d5be352ca01b5c1c3f is undefined
wasIHiddenBefore_f82bdc0c527541e68fc405e9ac70015b is undefined
wasIHiddenBefore_2d869e44f4c44454a8415eecbd64061e created as true
wasIHiddenBefore_f82bdc0c527541e68fc405e9ac70015b created as true
wasIHiddenBefore_1e16f2513f7842d5be352ca01b5c1c3f is undefined
wasIHiddenBefore_f82bdc0c527541e68fc405e9ac70015b is undefined

If anyone has insights into why this behavior is occurring and suggestions on how to ensure that these dynamic variables act globally across functions, your input would be greatly appreciated. Thank you.

Answer №1

When assessing whether <strong>window["wasIHiddenBefore_" + targetID] == true;</strong>, it is important to note that this is a comparison rather than an assignment. Even though "<em>… created as true</em>" is displayed in the log, the variable was never actually assigned the value. The correct syntax should be <strong>window["wasIHiddenBefore_" + targetID] = true;</strong>.</p>
</div></answer1>
<exanswer1><div class="answer accepted" i="37813520" l="3.0" c="1465900187" m="1465910987" v="1">
<p><code>window["wasIHiddenBefore_" + targetID] == true;
involves a comparison, not an assignment. Despite the message "… created as true", the variable remains unset. To assign a value, use
window["wasIHiddenBefore_" + targetID] = true;
.

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

What is the best way to adjust text across several lines to perfectly fit within a div's width?

http://codepen.io/anon/pen/oXGMQZ Is there a way to automatically adjust the font size of each span within a parent div so that it fills the width of the parent div? <div class="box"> <span class="fit">what</span> <span class="fi ...

Can the .scroll function be turned off when a user clicks on an anchor link that causes the page to scroll?

I am currently developing a timeline page and I want to implement a feature similar to the chronological list of years displayed on the right side of this webpage: As part of this feature, I have set up a click event which adds a circle border around the ...

What steps should I take to create this animation?

So here's my concept: I envision a circle div positioned in the center with multiple small lines extending outwards, resembling rays of sunlight. How should I go about achieving this effect? Would implementing JavaScript or utilizing CSS3 animations b ...

Can PHP be used to create a new page whenever Javascript history.go(-1) is triggered?

A PHP file (a.php) is currently sending the following headers: <?php header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Pragma: no-cache'); ? ...

Prevent clicking through slides on React by disabling the Swiper feature

Is there a way to handle the global document click event (using React hook useClickAway) so that it still fires even when clicking on a slide? For example, think of a circle in the header like an avatar dropdown - when you click on it, a menu pops up. Th ...

The function .remove() fails to remove a text node in Internet Explorer

Check out the code here: http://jsfiddle.net/6nN7G/ Utilizing a shopify app for star reviews that generates div.text - my aim is to eliminate the text indicating the number of reviews such as "19 reviews" and "3 reviews" from the HTML. This action is perf ...

Assurance of retrieving information

I am looking to extract specific information from the following website . I have implemented Promises in order to retrieve data about planets, then films associated with a particular planet object. My next goal is to access data within the species array ne ...

The challenge of mapping React Select

I have implemented react-select in my project and I am using it within a map function like this: renderItems() { this.props.items.map(item => ( <Select id="options" value={this.state.optionSelected} onChange={this.onChangeOpt ...

Integrating a conditional statement into the existing for loop code to conceal the covers

My goal is to hide the covers after they are clicked using an if statement within the for loop code. I believe this is where it should be placed. Trying to prevent this action from happening. https://i.sstatic.net/eLSto.png I made an attempt at achievin ...

Ways to divide different paths within a React Application

In my index.js file, I currently have the following code: <Router routes={routes} /> I want to move the routes section to a separate file. Here's what I've tried so far: routes.js export default ( <div> <Route path= ...

The function Page.render() will output a value of false

Currently, I am utilizing phantomjs to capture screenshots of multiple webpages. The code snippet below is what I have used to generate a screenshot image. var page = require('webpage').create(); page.viewportSize = { width: 1200,height: 800}; ...

Unveiling Elements as You Scroll Within a Specified Area

I have implemented a jQuery and CSS code to reveal my contact form as I scroll down the page. However, I am facing an issue with setting a specific range for displaying the element while scrolling. Currently, I have only managed to handle the scrolling dow ...

Utilizing JSON for the setAttribute() method

While I've made progress on this issue, I've encountered numerous confusing methods. The goal is to utilize the key:value pairs in attr{} for the setAttribute() function without relying on any framework. If anyone could provide a straightforward ...

Guide to importing a JSON file into Vue.js and HTML

I'm a beginner in Vue and not very familiar with HTML I'm attempting to import data from a JSON file into my interface to display it for the user. Below is the structure of the JSON: [ { "Title": "SOFT-STARTER", "Cod&q ...

clearInterval function is not functioning

Could this be a simple syntax error causing my frustration? The resizeTime variable seems to persist despite multiple attempts to clear it using clearInterval. Any thoughts on what may be going wrong here? Below is the code snippet: var resizeTime; // e ...

What is the most efficient way to clear the input field in Angularjs when the backspace or delete keys are pressed?

Is there a way to reset an input field with AngularJS when the backspace or delete keys are pressed? I've implemented this fantastic directive, and it's been working great, except for when the user uses the backspace or delete key to clear the f ...

What is the designated destination for JWT Tokens?

For my user login/signup process, I'm utilizing JWT and have a query regarding how the token is transmitted. At present, I am saving the token as a property in a JSON object on the server side, then passing it to the front-end. Upon receiving the obj ...

Node.js, Express continues to execute an if statement even if the condition is false

My goal is to determine whether the user signed in is an admin or not. User data is structured like this: [ { "isAdmin": "true", "_id": "60c6df22f25d381e78ab5f31", "name": "Admin", ...

What are the steps to make a basic slider with jQuery without using plugins?

<script> const animateImages = function(){ $("#slider").animate({"left":"-=1775px"},10000,function(){ $("#slider").animate({"left":"0px"},10000); animateImages(); }); }; animateImages(); </script> I incor ...

An easy guide to sorting outcomes using JSON

I have JSONResults in my Controller that contains all the data from a table. On the client's HTML detail view page, I am using JavaScript to fetch this data. How do I extract data from JSON where the client name is equal to klID (this is a JSON string ...