Unable to switch the variable's value from true to false

As I was updating my code, I realized that I needed to temporarily disable the "change" function. So, I introduced a variable called "enabled" and made the functions accessible only if var enabled == true. At the end of the functions, I set enabled = false; in order to disable the change(); function after its first execution. However, it seems like the function is still working perfectly. Can someone assist me with this issue?

//This function retrieves the ID of the images for conditional purposes
var enabled = true;

function getId(obj){
    var correctId = obj.getAttribute('id');
    return correctId;
}

if(enabled == true){
function drag(obj){
    var zIndexImg = 0;
    var id = obj.getAttribute('id');

    var img = document.getElementById(id);
    var imgPositionLeft = img.offsetLeft;
    var imgPositionTop = img.offsetTop;

        img.ondragstart = function(){
            return false;
        };

        function dropImage(e){
            // Dragging functionality
        }

        function change(id1,id2,div1,div2){
            // Image swapping logic
        }

        function drop(e){
            // Dropping image logic
        }

// Event listeners for dragging
img.addEventListener('mousedown', function(){
    document.addEventListener('mousemove', dropImage);
    document.addEventListener('mouseup', drop);
});
}
enabled = false;
}

http://jsfiddle.net/m8vvhf8e/3/

Answer №1

After some investigation, I discovered that the issue stemmed from me trying to change the ID within the same function where I was manipulating the images. This caused some complications in the functionality. To resolve this, I separated the tasks by creating one function for changing the images and another function for altering the IDs:

//function to swap the positions of images
            function change(id1,id2,div1,div2){

                img.removeAttribute('style');

                var imgDiv = document.getElementById(div1);
                var imgDiv_2 = document.getElementById(div2);
                var imgId = document.getElementById(id1);
                var imgId2 = document.getElementById(id2);

                imgDiv.innerHTML = imgId2.cloneNode().outerHTML;
                imgDiv_2.innerHTML = imgId.cloneNode().outerHTML;
}

//function to modify the image IDs
            function trocaId(id1,id2){
                var id_1 = document.getElementById(id1);
                var id_2 = document.getElementById(id2);

                    id_1.setAttribute('id',id2);
                    id_2.setAttribute('id',id1);
                }

//implementing the changes

            if(img.style.left >= '250px' && img.style.left <= '290px'){
                if(pegaId(obj) == 'teste1'){
                    change("teste1","teste2","img1","img2");
                    trocaId("teste1","teste2");
                }else if(pegaId(obj) == 'teste2'){
                    change("teste2","teste3","img2","img3");
                    trocaId("teste2","teste3");
                }

http://jsfiddle.net/v1u1xnwj/10/

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 have DOMDocument processed in PHP after running Javascript?

Currently, I'm working on a program that searches for tags. Unfortunately, I'm encountering difficulties retrieving tags created with JavaScript. ...

Height of inline-block list items in ul is not properly adjusted

I am working on a horizontal navigation bar using inline-block for the li tags. Here is the code snippet: <ul> <li><a href="#">HOME</a></li> <li><a href="#">FEATURES</a></li> <li><a href ...

Issue with AWS Datastore causing failure to save users in Android database

On my profile screen, I have implemented a code to save users in the database. The code works perfectly on iOS but throws an error on Android stating "Possible unhandled Promise Rejection" with "TypeError: Symbol.asyncIterator is not defined." Can someone ...

What sets the statements of ( for... in ) and ( for... of ) apart from each other?

Although I am familiar with the for... in loop (which iterates over keys), I recently came across the for... of loop for the first time, which apparently iterates over values. I find myself confused by this for... of loop. var arr = [3, 5, 7]; arr.foo = & ...

Typescript - utilizing forward and useref functionality

I am working with two components: const ComponentOne = () => { const a = React.useRef<WhatTypeGoesHere>(null); // ^^^^^^^^^^ encountering error - ComponentTwo is treated as value instead of type here const fn = () => { ...

the efficiency and speed of editing canvas rather than working with original images

Is it possible to apply effects like fades, movements, and other animations using a JavaScript library if I draw my images on different canvases? And if so, would doing this be more advantageous in terms of speed and performance rather than manipulating ...

What is the best way to include two additional columns next to the sidebar?

I'm having trouble adding another two-column section next to the sidebar. Is there anyone who can help me out? <!-- -------------Navigation Bar------------- --> <div class="sidebar"> <a class="active" href="#home">Home</a ...

What is the best way to store fonts for faster loading in NextJs?

Two fonts are being showcased to the user without any FOIT in place, causing a FOUT scenario where I want to avoid re-downloading fonts upon revisiting the page. To tackle this, I have implemented Font Observer to enhance FOUT fallback functionality withi ...

What are the best practices for storing an array of objects in MongoDB with Mongoose?

For my project, I needed to store data in a mongoDB document as an array of objects using Javascript, Node JS, Express framework, and Mongoose library. After researching online, I found two different methods to achieve this: Creating another sub-schema ...

Create a dynamic HTML table in React by leveraging arrays

I am working with two arrays: headings=['title1','title2'] data=[['A','B'],['C','D']] How can I efficiently convert this data into an HTML table that is scalable? title1 title2 A B ...

encountering difficulty while performing calculations within an HTML table

In my dynamic HTML table, I generate a tbody element upon changing the selected option. Within this table, there are 3 input fields: ItemName, which uses jQuery UI autocomplete to populate corresponding data from JSON format. The user then moves on to th ...

Achieve a main-menu container with a full width dropdown using Bootstrap 4

I want the dropdown to start from the initial position for all menus and maintain a width of 600px. Even if I attempt to open the dropdown for "Main Menu 2" or "Main Menu 3" or "Main Menu 4", the dropdown should always start from the position of "Main Men ...

Styling CSS for Centering a Heading on an Image's Center

Struggling to center an h3 heading in the middle of an image within a grid? Look no further, as I have 3 images across one row - four columns per image/heading. Check out the desired layout https://i.stack.imgur.com/8VFRt.png I've managed to center t ...

Issues with loading JSON data through JQuery

I am completely new to the process of loading JSON text using JavaScript or JQuery. JSON is a new concept for me as well. Currently, I have PHP providing me with some JSON text containing images stored on my server in the following format: [ [{ ...

Simple ways to personalize scrollbar in Material UI

Recently, I have been incorporating Material-UI into my React project to enhance its functionality. However, I encountered an issue where I was unable to customize the scrollbars within the Material-UI components. Here is the CSS code that I was using prio ...

How can I ensure that the NextJS Image component fills its parent div completely in terms of both height and width?

Having trouble getting the Image component to behave like the img element? Can anyone provide a solution for making Image achieve the same result as shown in the example below? <div style={{ width: "100vw", height: "100vh", display ...

How can I implement the Wordpress delete() function to remove a row from a table when a link is clicked?

I have a form on my site that collects data and stores it in the WordPress database. The information is then displayed on the same page in a table. Each row in the table has an "Action" column with a "Delete" link. My goal is to allow users to click the " ...

Reorganizing array sequence within a sortable list

I'm currently working with the react-beautiful-dnd module to build a draggable list. The backend data I receive is arranged according to the sequence field. Once an item is dragged and dropped, I utilize the reorder function to generate a new list. Ho ...

Tips on how to update the status variable to true depending on the index value

Once I click on the close button, the value immediately changes to "Fruit." How can I achieve this? For instance: Apple close Grapes close Pineapples close Alternatively, is there a way to set the state of "cancel" to true ...

Can CSS be used to separate elements within a div from the overall page styles, similar to how an iFrame functions?

Is there a way to isolate elements within a div, similar to how it would behave in an iFrame? I am facing issues with the global SharePoint styles affecting my app inside SharePoint. I want to completely disable these global styles so that my app only use ...