Using JQuery to reverse the action of hiding an image

Having some trouble with my Javascript and JQuery skills, so bear with me. I've set up a gallery of images where users can drag and drop them into a designated drop zone. Everything works fine when dragging an image from the gallery to the drop zone and back, but if I try to drag an image within the gallery itself, it disappears instead of reverting back. The console shows that the original image's display property is set to "none" even though I didn't specify this anywhere in my code (I suspect $(this).hide() is causing this). I've tried adjusting the CSS manually without success. Am I overlooking something? Happy to provide more details if needed. Unfortunately, it's too complex to create a JSFiddle for demonstration purposes. Thanks!

To clarify, I need a cloned image for dragging out of the scrollable div. However, using $(this).hide() to avoid having multiple copies seems to be the root of the issue. Ideally, I want the dragged image to revert to its original position inside the gallery rather than disappearing altogether.

$('.item').draggable({
            revert: "invalid",
            helper: 'clone',
            start: function () {
                $(this).hide();   
                $('.item').css('cursor', 'grabbing');
            },
            stop: function () {
                $('.item').css('cursor', 'grab');
            }
        });

        $("#arena").droppable({
            accept: '*',
            drop: function (event, ui) {
                $('.item').css('cursor', 'grab');
                var parentOffset = jQuery('#arena').offset();
                if(!ui.draggable.hasClass("newItem")) {
                    var new_item = $(ui.helper).clone().removeClass('item').addClass("newItem");
                    new_item.draggable({
                        revert: 'invalid',
                        start: function () {
                            $(ui.helper).hide();
                            $('.newItem').css('cursor', 'grabbing');
                        },
                        stop: function () {
                            $('.newItem').css('cursor', 'grab');
                        }
                    }).css({
                        'position': 'absolute',
                        'left': (ui.position.left - parentOffset.left) + 'px',
                        'top': (ui.position.top - parentOffset.top) + 'px',
                    });
                    $(this).append(new_item);
                    gallery_count--;
                }

Answer №1

After encountering the same issue of a pesky clone, I devised a solution that might help others facing this problem. My solution involved creating a flag variable named "moved," which is initialized as false. This variable is crucial in ensuring that an image dragged within the gallery remains visible while dragging and becomes hidden once it's dropped onto the dropzone. The "moved" variable transitions between true and false states appropriately to control the visibility of images in the gallery.

var moved = false;
$(function() {
    $('.item').draggable({
        helper: 'clone',
        revert: "invalid",
        start: function () {
            moved = false;
            $(this).hide();
            $('.item').css('cursor', 'grabbing');
        },
        stop: function (event, ui) {
            if ((ui.helper.hasClass("item") && moved == false)) {
                $(this).show();
            }
            $('.item').css('cursor', 'grab');
        }
    });

    $("#arena").droppable({
        accept: '*',
        drop: function (event, ui) {
            $('.item').css('cursor', 'grab');
            var parentOffset = jQuery('#arena').offset();
            if(!ui.draggable.hasClass("newItem")) {
                moved = true;
                var new_item = $(ui.helper).clone().removeClass('item').addClass("newItem");

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

Performing Batch Writes in Firestore using the Admin SDK

I have a massive ASCII flat file containing 1.5 million lines, which is essentially a list of parts from a manufacturer. I want to store this data in Firestore. Originally saved as a .csv file, the size was 250GB. After converting it to a JSON file using ...

The Strapi registration feature in version 4 is giving a "method not allowed 405" error, which

Feeling a bit confused with a Strapi query. I am currently working on v4 and trying to set up a registration feature. The code snippet for invoking the function is provided below. Everything seems fine, such as submitting function variables, etc. However, ...

Throw an error if the entry is not found in the Firebase database

I have an array containing various objects. Users should be able to access all objects using moduls/, and a specific one with moduls/$id. However, if the requested modul does not exist, the database should return an error to inform the client that there is ...

Tips for redirecting a port for a React production environment

I am currently setting up both Express.js and React.js applications on the same Ubuntu server. The server is a VPS running Plesk Onyx, hosting multiple virtual hosts that are accessible via port 80. To ensure these apps run continuously, I have used a too ...

Tips on saving this information in a MySQL database

I'm currently developing a php script that collects and saves links in mysql. However, I've encountered an issue where the script sometimes captures multiple links for the same download, as shown below: http://www.fileserve.com/file/XXXXXX http: ...

Using Jquery's getJson method, we can easily fetch and retrieve the appropriate JSON string by

I have the following code snippet at the beginning of the JSON url: if(isset($_GET['template']) && $_GET['template']=="blue") { $inifile_path="ctr/subthemes/blue/"; } else { $inifile_path="ctr/subthemes/fresh-n-clean/"; } Addi ...

Extracting Section Titles from INI using PHP

I've spent all night trying to perfect this code with no luck. I'm not even sure what to search for at this point. Here's the situation: I'm using PHP to parse .ini files into an HTML table. This is the code in my html file: <?php ...

Unable to assign an ID to an element in JavaScript, as it will constantly be undefined

Is there a way to automatically generate unique IDs for jQuery objects if they don't already have one? I need these IDs for future requests. I wrote the following code, but it doesn't seem to be working. The ID's are not getting set and the ...

What is the best way to retrieve the ajax response using Ajax.Responders in prototype.js?

I am looking to retrieve the response of each Ajax call within the function below Ajax.Responders.register({ onCreate: function() { }, onComplete: function(transport) { }, onSuccess: function(transport) { }, }); ...

Leveraging window.hash and the power of WordPress htaccess

I have a Wordpress website where I am using Ajax to display posts in a specific section. I am currently having Javascript add the hash tag like this: window.location.hash = id; Everything is working as expected. For instance, it changes the URL to www.my ...

Transform ISO-8859-1 encoding into UTF-8

Recently, I encountered an issue while sending a HTTP request using jQuery's ajax. The server, unfortunately, returns the response in ISO-8859-1 format while my page is set to UTF-8. This discrepancy causes some characters to become unreadable. How ...

How can one determine the most accurate box-shadow values?

I am trying to extract the precise box-shadow parameters from a CSS style rule generated by the server. My main focus is determining whether the element actually displays a visible shadow or not. There are instances where the shadow rule is set as somethi ...

Implementing promises when updating data in Firestore with JavaScript on Firebase

I'm looking to redirect the user to another page once their name has been updated. The challenge I'm facing is knowing when to use my location.replace function and how to incorporate promises in this situation. (username.value represents the new ...

Is it possible to attach React Components to Elements without using JSX?

In my React Component, I have the following code: import React, { useEffect } from 'react' import styles from './_PhotoCollage.module.scss' import PhotoCard from '../PhotoCard' const PhotoCollage = ({ author }) => { let ...

Getting rid of the Horizontal Scroll Bar

Having trouble with a persistent horizontal scrollbar in the "section3__container" container despite attempts to adjust size and overflow settings. Need assistance in removing this unwanted feature. <html lang="en"> <head> <m ...

Utilize the grouping functionality provided by the Lodash module

I successfully utilized the lodash module to group my data, demonstrated in the code snippet below: export class DtoTransactionCategory { categoryName: String; totalPrice: number; } Using groupBy function: import { groupBy} from 'lodash&apo ...

Error: The function res.json is not recognized. Despite searching through related inquiries, I cannot find a solution to my specific issue

Struggling to find a solution and avoiding repetitive questions, I am facing an issue with my bug tracker. After submitting the form and sending it to the server side, the bug is created in the database. However, when I save the bug using await bug.save() ...

Discovering the status of a wrapped component using Jest

const wrapper = mount( <ContextProvider> <FreeformEquationQuestionPractice question={question} /> </ContextProvider> ) console.log('freeform state: ', wrapper.childAt(0).instance().state) FreeformEquationQues ...

Efficient Pagination in CakePHP Using Ajax Search Functionality with POST Data

I am in the process of implementing a search functionality in my CakePHP 2.x project. Below is the controller code I have written: public function admin_index() { $this->Customer->recursive = 0; $this->Paginator->settings = array( ...

Understanding the hierarchy of LESS css class structure is crucial for

In my chat contact list, each contact can have a different state represented by classes: .online .offline .online .selected .offline .selected Here are the corresponding styles (example): .online { background-color: #fff; p { color: #000; } } . ...