What is the process for defining an outcome when a draggable element is placed into a droppable area using Jquery?

Currently, I am working on a task where I need to increase the value of a counter (var counter = 0;) every time a draggable image is dropped into a dropzone, which is also an image rather than a div.

$( "#goldbag" ).draggable({ revert: "invalid", containment: "parent" });
$( "#jack2" ).droppable({
    drop: function(event, ui) {
        draggedObj = ui.draggable.attr('id'); 
        $("#"+draggedObj).fadeOut(function() { $(this).remove(); });
        $( "img" ).draggable({ disabled: true });
    }
});

The current functionality of this code is that it makes the droppable image fade out when dropped on the target. However, I aim to increment the counter by 1 before or after the image fades out.

Please note that both #goldbag and #jack2 are images represented as <img> elements within a shared parent container div.

Answer №1

If you want to enable the ability to drag and drop an item multiple times while incrementing a counter, you can simply extend your drop callback function. Here's a basic example to demonstrate this functionality.

This code snippet is adapted from the official jQuery UI documentation available at: https://jqueryui.com/droppable/#default

$(function() {
  var $counter = $("#counter");
  var count = 0;
  $("#draggable").draggable();
  $("#droppable").droppable({
    drop: function(event, ui) {
      $(this)
        .addClass("ui-state-highlight")
        .find("p")
        .html("Dropped!");
      count++;
      $counter.html(count);
    }
  });
});
#draggable {
  width: 100px;
  height: 100px;
  padding: 0.5em;
  float: left;
  margin: 10px 10px 10px 0;
}
#droppable {
  width: 150px;
  height: 150px;
  padding: 0.5em;
  float: left;
  margin: 10px;
}
<link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>


<div id="draggable" class="ui-widget-content">
  <p>Drag me to my target</p>
</div>

<div id="droppable" class="ui-widget-header">
  <p>Drop here</p>
</div>

<p>Counter: <span id="counter">0</span>
</p>

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

Use jQuery to remove an ID from an element using AJAX to interact with a database, then update

Hello, I am currently using jQuery to retrieve ids of multiple fields with ajax and send the data to be deleted via php. Despite being able to delete one item successfully, I am struggling to remove other ids. For example: Within a for loop that retrieves ...

html scroll to the flickering page

Why is it that when a user clicks on a link in the list, the browser flickers? This issue becomes especially noticeable if a user clicks on the same 'link' twice. Is there a solution to prevent this from occurring? The problem also seems to aris ...

When submitting, Redux objects are being submitted with empty values

Whenever I try to submit my form, the object is being submitted empty. This was confirmed using the redux dev-tool, where it shows that the object is empty upon submission. The expected behavior is for a card to appear on the DOM with the information enter ...

jQuery has been utilized to clone a form, resulting in the fields becoming inactive

I have a basic form with some fields that are affected by the click event. In addition to this, I am duplicating the form and appending it (with the intention of renaming the fields, but I have not succeeded yet). The problem I am facing is that after cl ...

Calculating the time gap between two consecutive "keyup" occurrences

I am in need of creating a basic point of sale system using Javascript. I have a barcode scanner that functions like a keyboard. My goal is to automatically identify when the input is coming from the barcode scanner and then generate a report with the sc ...

Utilizing the splice method across multiple instances of a string

When facing a string like "This website is blocked by administrator. Please get the admin permissions. You will be allowed only if permission is granted" that needs to be split into three lines for better readability, one solution is using the splice metho ...

When imported, Node / JS instantly generates a new instance

Is there a way to instantiate a class without importing it first and using new afterward? Instead of var mainClass = require('../dist/main'); // has "class Main { ... }" var mainInstance = new mainClass(); I am looking for something like var ...

Unable to access the URL slug within the client component in Next.js version 13

In my upcoming project with Next 13, I have a client-side component that is being rendered under the route /journal/[date] Unfortunately, I'm facing an issue trying to extract the date from the URL. I attempted to use: import { useRouter } from &apos ...

Setting up Scss and purgeCss configuration in Next.js custom postCSS configuration: A step-by-step guide

My current project is using Scss in combination with Bootstrap for design. I have implemented purgeCss to remove unused Css, and customized my postcss.config.js file as follows: module.exports = { plugins: [ "postcss-flexbugs-fixes", [ " ...

Design with Internal Elements

Seeking a pattern similar to the code snippet provided below. Interested in learning how to create MyComponent. render(){ <MyComponent> <MyComponent.Something> These children will be displayed </MyComponent.Something> <MyC ...

How can I set a minimum height for a table on my website?

Is there a way to make a table that is at least 50px in size, but can still enlarge if there is a lot of text inside? I'm not sure if this even makes sense, but any help would be appreciated. Thank you! ...

Is IPv6 like a JavaScript string in any way?

Introduction In the era of IPv4, life was simpler as IPv4 addresses could easily be converted into 32-bit integers for various calculations. However, with the introduction of IPv6, things have become more complicated due to the lack of native support for ...

JavaScript comparing variables to nested object properties

items resembling this are heading my direction: var info = { a0: { name: 'lengthy title 0', var1_min: '10', var1_max: '99', select: ['alpha', 'gamma'], display: 'value0' }, b12: { ...

Dynamically loading an AngularJS controller

I am faced with the challenge of integrating an Angular app with dynamically loaded controllers into an existing webpage. Below is a code snippet where I have attempted to achieve this based on my understanding of the API and some research: // Create mod ...

Coinciding titles within flot pie chart

I am facing an issue with overlapping labels in my pie charts generated using jquery flot, especially when the chart pieces are very small. Is there a recommended solution to prevent this overlap? Below is the configuration for my current pie chart: ser ...

Can you generate a new element based on a template element?

I'm encountering an issue with the following code snippet: template = $("#template"); $(template).attr("id", "newid"); $(template).appendTo("body"); My goal is to assign an id to the template and then modify its content. However, I seem to be direc ...

I am facing an issue with body-parser not properly processing my request in express.js

Utilizing the Controller in my project. Snippet from app.js: var express = require('express'); var app = express(); const routes = require('./Routes/route'); const bodyParser = require('body-parser'); app.use('/', ...

Eliminate numerous items from an array containing objects

Looking for a way to remove specific objects from an array of objects within another object. I want to delete multiple items simultaneously, but when attempting with splice, it shows up as undefined. This is the snippet of code I'm working with: ...

What is causing the issue of subdomains not functioning properly in express.js?

Currently, I am conducting some local experiments and have made changes to my hosts file. Here are the entries: 127.0.0.1 example.dev 127.0.0.1 www.example.dev 127.0.0.1 api.example.dev Below is the code I am using: var subdomain = req ...

Guide on populating a Vue.js input field with a value retrieved from a JSON object

Could someone please assist me with a problem I am encountering? I need to extract and display the values from an input form for "name" and "position", but the data is in JSON format. {"id":5,"name":"the name","pos":"the position"} This code snippet repr ...