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

Clicking on the overlaying divs in the slideshow does not trigger any changes when clicked

My question is about the behavior of the href attribute in a fade-style animation. Even when different containers are visible, the href value remains constant. Below is the HTML code: <div id="teaserslider"> <ul> <li> ...

Centralizing the Accordion header and expansion icon in React with Material-UI

I'm currently incorporating the Accordion feature from Material-UI library into my React project: My goal is to ensure that the accordion summary (header with "Accordion 1", "Accordion 2") is centered, and the expand icon (arrow) is also centered rig ...

Why does my CSS attribute selector fail to update when the property's value changes?

Context: I'm working on a React-based web app that utilizes traditional CSS loaded through an import statement. In order to create a slider functionality, I have applied a CSS selector on the tab index attribute. Challenge: The issue I am facing is t ...

Switch up the appearance of a document by manipulating the stylesheet using a select tag

I'm currently facing an issue with the implementation of a drop-down box on my website for selecting different themes. Despite having the necessary javascript code, I am unable to get it working correctly. Here's the snippet: //selecting the sele ...

regex execution and testing exhibiting inconsistent behavior

The regex I am using has some named groups and it seems to match perfectly fine when tested in isolation, but for some reason, it does not work as expected within my running application environment. Below is the regex code that works everywhere except in ...

Using JavaScript to parse JSON data containing additional curly braces

Looking at this JSON object: var dataObj = { data: '\n{ sizeMap:{\nxSizes: "REGULAR|SMALL", \ncurrItemId: "",\ncurrItemSize: "",\nmanufacturerName:"Rapid",\npartNumber: "726G", \nsuitStyle: "R",\nhasSC: "",&bso ...

Integrating redux-form with the react-widgets DateTimePicker component

I am currently working on a project using ReactJS with Redux and I am trying to incorporate a form similar to the one shown in this example: Most of the components are working well, but I am encountering an issue with the DateTimePicker due to the momentL ...

Error message: "User not found during passport authentication"

I am currently in the process of developing an authentication system for my website. However, I am encountering a specific error message when attempting to log in with any combination on the website: ReferenceError: user is not defined user is not define ...

Encountering an ElementClickInterceptedException while trying to click the button on the following website: https://health.usnews.com/doctors

I am currently in the process of extracting href data from doctors' profiles on the website . To achieve this, my code employs Selenium to create a web server that accesses the website and retrieves the URLs, handling the heavy lifting for web scrapin ...

Instructions on how to dynamically update a form field based on the input in another field using conditional statements

I'm seeking advice on how to automatically update a field based on user input without the need for manual saving. For example, if the user types '95' in the input field, the equivalent value displayed should be '1.0' in real-time. ...

Module 'prompt-sync' not found

When attempting to take user input in Node.js using the prompt module, I encountered the following error message: node:internal/modules/cjs/loader:998 throw err; ^ Error: Cannot find module 'prompt-sync' Require stack: - D:\Code\C+ ...

Is there a way to exclude a specific div based on two select choices?

Check out my Fiddle demonstration here $('select#classes').on('change', function() { var selectedClass = $(this).val(); $('.col-sm-6:not(:contains(' + selectedClass + '))').hide(); $('select#subjec ...

Iterating over objects within a nested array using ng-repeat

My back-end is sending me an array of string arrays (Java - CXF-RS). The length of each array within the string arrays ranges from 1 to n. In order to display this data on my front-end, I am utilizing ng-repeat. Everything is functioning correctly with o ...

Scroll horizontally through a dynamically sized div with fluid width using jQuery, pause at the beginning and end, and retrieve the width of the

It seems like what I really need is a customized jquery slider, as the ones I've experimented with (caroufredsel, elastislide, smoothdivscroll) don't quite meet my requirements. Many of them come with unnecessary extra features that I don't ...

Angular - navigate to the element that was clicked

It seems like there may be a simple solution that I'm overlooking. I have a container element with an ng-repeat on the child element as shown below: <div id="container"> <div class="activity" ng-click="myFunc($element)"> </div ...

Intercept Axios Responses - Retrieving API Responses for HTTP Statuses that are not in the 200 range

I've set up a custom Axios instance with interceptors for handling responses. As per the Axios documentation, the success interceptor is triggered for 2xx statuses while the error interceptor handles any other status codes. My goal is to show an error ...

Implementing microdata without visibly displaying tagged entities on the webpage

I have a query regarding the implementation of Microdata on my webpage where tagged entities are not being displayed. For instance, I want to talk about two individuals in a paragraph without their names appearing on the webpage. Is there a method to only ...

How to choose elements using jQuery according to their CSS properties?

Seeking a solution to a unique challenge I've encountered. The website I frequent has found a way to bypass my uBlock extension by using a script that generates random element classes, such as: <div class="lcelqilne1471483619510ttupv"></div& ...

Display only the relevant search results using ng-show in AngularJS

By utilizing the code below, I am able to filter results where all entries are displayed on the page: <body ng-app=""> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name: ...

"Vue js: Embracing Labeling and Agile Transformation in Dynamic

Is it possible to dynamically change the input field's type and label between text, email, and number in Vue.js? I am new to this framework and would like to learn how to do this. <input type="email"> ...