Prevent dragging functionality after being dropped onto a droppable area

I am currently working on a drag and drop project and have encountered a minor issue. My goal is to disable the draggable item after it has been dropped onto the droppable area. I have created a function called disableDrag, but I am receiving an error in the console and the function is not executing as expected. Does anyone have any insights into why this might be happening? Additionally, I am open to suggestions for alternative approaches to achieve this functionality.

Here is the HTML setup:

<div class="container">

  <div id="key" class="fragment">
    <div class="key"></div>
  </div>

  <div id="dragonkey" class="fragment">
    <div class="key"></div>
  </div>

  <div id="inventory">
    <div class="slot" id="slot1"></div>
    <div class="slot" id="slot2"></div>
  </div>

</div>

CSS styling:

.container{
  width:300px;
  height:300px;
  background-color:#ccc;
}
#key, #dragonkey{
  width:20px;
  height:20px;
  position:absolute !important;
  z-index:999;
  cursor:pointer;
  background-color:DarkGoldenRod;
  transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
    -moz-transform:rotate(45deg);
    -o-transform:rotate(45deg);
}
#key{
  top:5%;
  left:5%;
}
#dragonkey{
  top:15%;
  left:5%;
}
#inventory{
  width:68px;
  height:68px;
  position:relative;
  float:right;
  margin:5% 5% 0 0;
  transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
    -moz-transform:rotate(45deg);
    -o-transform:rotate(45deg);
}
.slot{
  border:2px solid #fff;
  width:30px;
  height:30px;
  float:left;
}
#slot1, #slot2{
  background-color:rgba(0,0,0,1);
}

.ui-droppable-active{
  background-color:rgba(184,134,11,0.7) !important;
}

Below is the jQuery setup:

// JavaScript document

$(document).ready(function() {

  $("#key").draggable({
    containment: ".container"
  });

  $("#dragonkey").draggable({
    containment: ".container"
  });

  $("#slot1").droppable({
    accept: "#key",
    drop: dropAnimate
  });

  $("#slot2").droppable({
    accept: "#dragonkey",
    drop: dropAnimate
  });

  function dropAnimate(event, ui) {

    console.log( $(ui.draggable).attr('id'));

    var $this = $(this);

    var width = $this.width();
    var height = $this.height();
    var cntrLeft = (width / 2) - (ui.draggable.width() / 2);
    var cntrTop = (height / 2) - (ui.draggable.height() / 2);

    ui.draggable.position({
      my: "center",
      at: "center",
      of: $this,
      using: function(pos) {
        $(this).animate(pos, "slow", "linear");
      }
    });
    disableDrag();
  }

  function disableDrag () {
    $(this).draggable({
      disabled: true
    });
    console.log("DISABLED");
  }


}); <!-- END OF DOCUMENT READY -->

Answer №1

To apply the disabled: true setting on the ui.draggable element, you can use this code:

ui.draggable.draggable({disabled: true});

Take a look at this example:

// Here is an example in JavaScript
$(document).ready(function() {

  $("#key").draggable({
    containment: ".container"
  });

  $("#dragonkey").draggable({
    containment: ".container"
  });

  $("#slot1").droppable({
    accept: "#key",
    drop: dropAnimate
  });

  $("#slot2").droppable({
    accept: "#dragonkey",
    drop: dropAnimate
  });

  function dropAnimate(event, ui) {

    console.log( $(ui.draggable).attr('id'));

    var $this = $(this);

    var width = $this.width();
    var height = $this.height();
    var cntrLeft = (width / 2) - (ui.draggable.width() / 2);
    var cntrTop = (height / 2) - (ui.draggable.height() / 2);

    ui.draggable.position({
      my: "center",
      at: "center",
      of: $this,
      using: function(pos) {
        $(this).animate(pos, "slow", "linear");
      }
    });
    
    ui.draggable.draggable({disabled: true});
  }

}); <!-- END OF DOCUMENT READY -->
.container{
  width:300px;
  height:300px;
  background-color:#ccc;
}
#key, #dragonkey{
  width:20px;
  height:20px;
  position:absolute !important;
  z-index:999;
  cursor:pointer;
  background-color:DarkGoldenRod;
  transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
    -moz-transform:rotate(45deg);
    -o-transform:rotate(45deg);
}
#key{
  top:5%;
  left:5%;
}
#dragonkey{
  top:15%;
  left:5%;
}
#inventory{
  width:68px;
  height:68px;
  position:relative;
  float:right;
  margin:5% 5% 0 0;
  transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
    -moz-transform:rotate(45deg);
    -o-transform:rotate(45deg);
}
.slot{
  border:2px solid #fff;
  width:30px;
  height:30px;
  float:left;
}
#slot1, #slot2{
  background-color:rgba(0,0,0,1);
}

.ui-droppable-active{
  background-color:rgba(184,134,11,0.7) !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<div class="container">

  <div id="key" class="fragment">
    <div class="key"></div>
  </div>

  <div id="dragonkey" class="fragment">
    <div class="key"></div>
  </div>

  <div id="inventory">
    <div class="slot" id="slot1"></div>
    <div class="slot" id="slot2"></div>
  </div>

</div>

Answer №2

When working with the disableDrag function, make sure to correctly reference the element being dragged instead of pointing to the Window object. This can be fixed by passing the draggable element as an argument when calling the function like so: disableDrag($this);. Additionally, modify the function to include an argument function disableDrag(item) and replace

$(this).draggable({disabled: true})
with
$(item).draggable("option", "disabled", true);
.

Take a look at this jsFiddle example for more clarity.

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

Navigating through a JSON document using jQuery

I've been attempting to iterate through a JSON string (located in a separate file named language.json) but I can't seem to make it work { "language": [ { "name": "English Languages", "values": ["English 1", "English 2", " ...

Unable to transform Table layout into DIVs

My form for data input consists of labels with inputs, but the labels are localized so I am not sure about the length of text for different languages. To tackle this issue, I initially used a table layout: <table> <tr> <td> ...

Arrange the table by column following a service request

Is there a method to organize the table below once it has been loaded? I am utilizing Google API to retrieve distance matrix data, but I want the table to be sorted by distance. However, this sorting should take place after the Google service call is comp ...

Looking to streamline your design? Find out how to translate multiple elements to the same position seamlessly

Greetings! This is my debut post on this platform. I am currently engrossed in a project that has presented me with a challenge, and I'm reaching out to seek your insights on a potential solution. Here's the scenario: I have a parent div containi ...

query in PHP to display specific data

Seeking guidance for developing a document tracking system using PHP. Struggling with defining the correct title for my project and unable to generate relevant keywords for search queries. The main issue pertains to determining how the system can validat ...

The issue of losing session data in Laravel 4 due to multiple AJAX requests

There is an issue on my page where photos are lazy loaded via AJAX, and sometimes all session data gets lost while the photos are loading. This problem does not occur consistently every time the page is loaded. I have already checked for session timeout or ...

Confirmation dialog with user-defined button text

When the confirm prompt box is used, it typically displays "ok" and "cancel" buttons. I am looking to customize the label text for the buttons to read as Agree and Not Agree instead. If you have any suggestions on how to achieve this modification, please ...

The functionality of if and else statements within local storage is not functioning as

I've been working on implementing a styleswitcher for my website. I successfully created a dropdown menu and saved it in localstorage. However, I'm facing an issue when trying to use the localstorage information to trigger an alert() through if a ...

Achieving Vertical Alignment of Two Divs with CSS

I've come across several solutions to my issue, but none of them seem to work in my current situation. I have a banner at the top of my site with two floated columns, and suspect that the navigation menu in the right column may be causing the problem. ...

What is the alternative to jQuery.submit now that it has been deprecated in version 3.3?

After reviewing the source code, you will find: /** * Attach an event handler to the "submit" JavaScript event, or trigger that event on an element. * * @param handler The function to be executed each time the event is triggered. * @see {@link https:/ ...

Creating a Pinterest-inspired CSS layout from scratch without using any additional plugins

If you want to check out my code on jsfiddle and learn how to create a style similar to Pinterest without using plugins, click on the link below. Within the code, there is a square Node.js diagram that I would like to position down the left side. http://j ...

Utilize the scrollIntoView method within a jQuery function

My current setup involves using JQuery's show and hide function. Essentially, when an image is clicked, it triggers the display of an information log. The issue I am facing is that this log opens at the top of the page, whereas I would like it to scro ...

IE11 experiences frequent crashes when running a web application utilizing the Kendo framework and JavaScript

I am experiencing difficulties with my ASP.NET MVC application that utilizes Kendo UI and jQuery. Specifically, when using Internet Explorer 11, the browser crashes after a short period of usage. The crash does not seem to be linked to any specific areas o ...

Why does a black model appear when loading a GLTF model with materials?

I am currently attempting to load a 3D model in glb format. Below is the code snippet: Expected Outcome: Image Current Outcome: Image var renderer = new THREE.WebGLRenderer(); renderer.setSize(1000, 1000); renderer.setPixelRatio(window.devicePixelRati ...

Steps to position an image without a background in the middle of a smaller container:

My HTML includes the following code: <div style="width:400px;height:300px;overflow:hidden;"> <img src="http://d39kbiy71leyho.cloudfront.net/wp-content/uploads/2016/05/09170020/cats-politics-TN.jpg" /> </div> Take a ...

Verify with PHP

I am looking to add a simple button on my HTML page that can trigger my PHP script when right-clicked. I have attempted to do this with the code below, but unfortunately, I haven't had much success so far: //My html code <!DOCTYPE html> <hea ...

Footer not being pushed down by content in mobile view on page

Hello everyone, Can you assist me with a query, please? My form works perfectly fine in desktop view, but it gets cut off on mobile view and I'm unsure of the reason why. Here is my code: .upload-pic { position: absolute; max-width: au ...

Ionic - encountering crashes with ion-nav-view on emulator

I am encountering an issue with ion-nav-view. Whenever I try to use it, the emulator displays a black screen, but it works perfectly fine in ionic serve. I suspect it may be a syntax error causing this problem. Interestingly, when I create a blank projec ...

Implementing ajax functionality to dynamically insert various user inputs upon a button click

I'm searching for resources or materials that explain how to use jQuery and AJAX to create a feature where multiple inputs can be added to a form with just one click. Google's Gmail client is a perfect example of this functionality, as it enables ...

Using JQuery to loop through elements when clicked

I've been experimenting with different methods to iterate through a series of 4 li elements, each having a class of "item_n" where n is a number from 1 to 4. I want the iteration to increase by 1 with every click. Despite my efforts, my code isn' ...