Permit the presence of a single draggable item within a droppable area at any given time, while allowing any

Currently, this is my setup for draggable and droppable sections:

$('.planets').draggable({
    opacity: .4,
    create: function(){$(this).data('position',$(this).position())},
    cursorAt:{left:15},
    cursor:'move',
    start:function(){$(this).stop(true,true)},
    revert : 'invalid'
});

$('.targets').droppable({
    greedy: true, ///////////////
  drop: function( event, ui ) {
    $( this ).addClass( "dropped-highlight" );
    $(this).droppable('option', 'accept', ui.draggable); ////////
    $(this).append(ui.draggable); /////////
    snapToMiddle(ui.draggable,$(this)); //This function snaps the draggable to the middle of the droppable
  },
  out: function( event, ui ) {
    $(this).removeClass( "dropped-highlight" );
    $(this).droppable('option', 'accept', '.planets'); /////////
  }
});

I have managed to restrict stacking multiple draggables in a single droppable. I aim to allow only one droppable in a draggable at a time. After removing a draggable, a new one can enter that area. The lines marked with /////// were recently added to achieve this.

Edit: This solution is effective!

$('.planets').draggable({
    opacity: .4,
    create: function(){$(this).data('position',$(this).position())},
    cursorAt:{left:15},
    cursor:'move',
    start:function(){$(this).stop(true,true)},
    revert : 'invalid'
});

$('.targets').droppable({
  drop: function( event, ui ) {
    if(!$(this).hasClass('dropped-highlight')){
        $( this ).addClass( "dropped-highlight" );
        $(this).droppable('option', 'accept', ui.draggable);
    }
  },
  out: function( event, ui ) {
    $(this).droppable('option', 'accept', '.planets');
            $(this).removeClass( "dropped-highlight" );
  }
});

Answer №1

Make sure to check if the element contains the "dropped-highlight" class before appending it, and remember to remove it when leaving the droppable area.

You can achieve this with the following (example code):

if !this.hasClass('dropped-highlight'){

(your code)

}

and in drop: this.removeClass('dropped-highlight').

The second part is already implemented, so just add the first part as shown above.

if !$(this).hasClass("dropped-highlight"){
  $( this ).addClass( "dropped-highlight" );
  $(this).droppable('option', 'accept', ui.draggable);
}

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

The functions.php file is failing to send an ajax request

I am currently working on a custom post type slider in WordPress using shortcode. Everything works fine when I retrieve data from other pages, but I encounter issues when trying to fetch the same data from the shortcode of the custom post type that is writ ...

Tips for retrieving the unique Button ID upon submitting a form

<form action="" method="post" id="all-student-reservations-form" class="form-block"> <label style="display: inline-block; vertical-align: bottom;">Type<br> <select name="drlist-type" id="drlist-type" class="input-la ...

Show unique language text in the <noscript> element based on the user's browser language

I am just starting out with HTML, and I would like to show a message if JavaScript is disabled. To do this, I have placed the message within the <noscript> tag, which is working perfectly. <noscript> Need to enable Javascript. </noscript> ...

The fancybox link functions properly on the initial attempt, but fails to work on subsequent

I've been working on a project with a div that contains blog posts linking to individual pages, and I wanted to display these linked pages in a modal using Fancybox. However, I've encountered an issue where only the first link clicked actually op ...

Issue with ASP.NET server side control not being triggered within a JQuery modal dialog

My ASPX page has 2 jQuery popups, each with a pair of server-side buttons. However, the issue is that these buttons do not fire when pressed. I suspect it's an issue with the jQuery popup itself. How can I solve this problem? EDIT: See code below &l ...

Tips for achieving a gradual shadow effect on edges in THREE.js

I have come across some 3D scenes where I noticed a subtle gradient shadow near the edges of objects. This seems to enhance the definition between the two faces. How can we achieve this effect? Is it a result of shadow technology or light reflection techni ...

Live events are not showing up upon page load, but they work flawlessly on the local server

I am currently developing a project using Laravel and Angular. In this project, I am implementing the angular ui-calendar as well as utilizing the jQuery context menu plugin to create dynamic menus for each event. The versions I am working with are fullca ...

Ways to resolve the error message "TypeError: 'setOption' is not a function on type 'MutableRefObject' in React"

CODE export default function EChart({ option, config, resize }) { let chart = useRef(null) let [chartEl, setChartEl] = useState(chart) useEffect(() => { if (resize) { chartEl.resize() } if (!chartEl.cu ...

Getting to a nested key in a JSON object with JavaScript: a step-by-step guide

Currently, I'm working with a JSON file and need to extract the fileName tag for use. { "dataset": { "private": false, "stdyDscr": { "citation": { "titlStmt": { "titl": "Smoke test", "IDNo": ...

Using the d3.js library to format numbers displayed in tooltips

I'm currently working on a d3 graph that includes a tooltip showcasing the number of units. My goal is to format these numbers in a way that they appear as "Units: 225,247" rather than the current format of "Units: 225247." var div = d3.select(' ...

Filter out only the necessary values from JSON data

Why mark a question as duplicate? Is it for points or to be a wiseass? You can't assume a question won't help someone. The answers from the "duplicated" question didn't answer my question, but the person who answered MY question did. -EDIT ...

The onchange event for the input type=file is failing to trigger on Google Chrome and Firefox

Update: Solved: http://jsfiddle.net/TmUmG/230/ Original question: I am facing an issue with handling image/logo upload alongside a hidden input type=file: <form class="image fit" id="theuploadform"> <input title="click me to chan ...

Tips for updating a button's text when clicked

One feature on my webpage is a "Read More" button that, when clicked, expands to reveal additional information (button not pressed). Here is how it appears once the user has clicked the button (button pressed). Despite my research on Stack Overflow, I have ...

Coloring vertices in Three.js IcosahedronGeometry

I have been experimenting with dynamically changing the color of a selected vertex. Based on my work at https://jsfiddle.net/pmankar/m70cpxes/, I constructed an IcosahedronGeometry point cloud geometry. When a click event occurs, my goal is to alter the co ...

Is it necessary to have bidirectional relationships in Sequelize?

In my database, I have two existing tables: "user" which contains columns "id" and "depId", and "department" with columns "id" and "name". The column user.depId is a foreign key referencing department.id. Now, I want to create a sequelize model for this r ...

Tips for managing the dimensions of a select element in bootstrap

I need assistance with adjusting the width of select tags in my form so that they align properly with the text boxes above. Here is the HTML code: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/& ...

Modify the background color of a specific bar across multiple charts when hovering or clicking - utilizing chart.js

I have multiple chart.js canvas elements on a webpage. The goal is to be able to quickly identify and highlight the same bar value across all the charts. For example, when I hover over a bar called "Thu" on the first chart, I want to automatically search f ...

Making a Connection with Ajax in Django: Adding Friends

I have been exploring the capabilities of Django-Friends My goal is to make it so that when a user clicks on the add friend button, it either disappears or changes to say "Request sent". However, I am encountering an issue where the button does not disapp ...

Obtaining AJAX Table Data in Laravel 5.2

When I click the button to display the table, how can I use AJAX in Laravel to update and show all records with new content? The code provided is not working for me. This is my table: <table class="table table-condensed text-right"> ...

React-Native - Issue with TypeError: attempting to call a function that is undefined (specifically when using the 'object.map' method)

I've tested everything from the itemList to the reducer and action, it's working fine and successfully deleting the desired item. However, I encountered an error afterwards. I'm not sure where I went wrong. Can someone guide me on what steps ...