Jquery Droppable issue arising with dynamically added DIVs

I am facing a similar issue as described in this question and this one

I am trying to implement drag-and-drop and resize functionality. It is working fine for static elements, but I encounter issues when adding dynamic divs. The resize property works properly, but the droppable functionality does not work. Despite spending a lot of time researching and applying solutions, I have had no success.

You can find an example on JSFiddle

How can I resolve this problem?

Here is the code snippet:

CSS

#Section1 > div {
    display: table-cell;
    /*width: 1%;*/
    border-right: 1px dotted red;
    text-align: center;
}

HTML

<input type="button" class="Mybutton" value=" Add div" />
<br />
<div class="selectorField" style="height: 100px; width: 100px; background-color: green;"></div>

<div id="Section1" style="height: 100px; line-height: 20px; width: 100%; border: 1px dotted red; display: table;">
    <div class="well droppedFields ui-sortable Resizable" style="width:73px;"></div>
</div>

JQUERY

function makeDraggable() {
    $(".selectorField").draggable({
        containment: $('body'),
        helper: "clone",
        stack: "div",
        cursor: "move",
        cancel: null
    });
}

$(function () {
    var _ctrl_index = 1001;
    $(".Resizable").resizable({ handles: 'e' });
    makeDraggable();

    $(".droppedFields").droppable({
        accept: ":not(.ui-sortable-helper)",

        drop: function (event, ui) {
            var draggable = ui.draggable;
            draggable = draggable.clone();
            draggable.appendTo(this);
            makeDraggable();
        }
    });

    var count = 0;
    $('.Mybutton').click(function () {
        count++;
        if (count < 5) {
            var a = $("<div class='well droppedFields ui-sortable Resizable'></div>").appendTo("#Section1");
            a.droppable();
            a.resizable({ handles: 'e' });
        } else {
            alert('No more divs to add');
        }
    });
});

I appreciate any assistance with resolving this issue.

Answer №1

Ensure you make the dynamic div droppable. I have made changes to your JSfiddle to show how this can be done. Check line 52 for details.

Answer №2

For further details, please refer to this fiddle.

http://jsfiddle.net/tdorbbv6/8/

        function makeDraggable() {
        $(".selectorField")
            .draggable({
                containment: $('body'),
                helper: "clone",
                stack: "div",
                cursor: "move",
                cancel: null
            });
    }
function Droppable(){
 $(".droppedFields").droppable({

            accept: ":not(.ui-sortable-helper)",


            drop: function (event, ui) {


                var draggable = ui.draggable;
                draggable = draggable.clone();
               draggable.appendTo(this);
             //   $(ui.draggable).hide();

                makeDraggable();
            }
        });
}
        $(function () {
        var _ctrl_index = 1001;
        // function docReady() {


       $(".Resizable").resizable({ handles: 'e' });

        makeDraggable();




   var count = 0;
        $('.Mybutton').click(function () {
            count++;
            if (count < 5) {
                // alert("aa");

                var a = $("<div class='well droppedFields ui-sortable Resizable'></div>").appendTo("#Section1");
               Droppable();
                //a.droppable();
                //a.resizable({ handles: 'e' });
                //  a.makedroppable(); { handles: 'e' }

            }
            else {
                alert('No more divs to add')
            }
        });
    });

Following the addition of dynamic controls, remember to reassign events to those controls. Place your droppable code within function quotes.

Once you have added controls, simply invoke the function to bind the droppable event.

I trust this information will be beneficial.

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

Is there a way to invoke a function within a mat-error element?

I need to display an error message in my input field! The function will return true if both passwords match, otherwise it will return false. How can I invoke a boolean function inside mat-error! My Function: checkPasswords(): Boolean { // 'passwords& ...

Identify the moment when the SPAN element reappears in sight

I have a question that may have been asked before, but I haven't found a satisfactory answer yet. Within my HTML code, I have a SPAN element with an onclick event, like so: <span onclick='loadDiv()'>Text</span> When a user cli ...

The <img> element is able to fill an entire div while maintaining its original aspect ratio

I am currently facing a challenge with implementing a responsive gallery slider in Bootstrap. In order to achieve responsiveness, I need to use properties like max-height. The issue arises from the fact that the images in the gallery can vary in size and ...

Tips for preventing timeouts when posting data to Heroku servers

I have a Ruby on Rails application deployed on Heroku. The app includes 8 optional text fields that users can choose to fill or leave empty as needed. However, the more text fields a user fills out, the heavier the processing load on my app. If there are ...

The appearance of random instances of the letter "L" within text on Internet Explorer 8

Help needed! I'm encountering an issue where mysterious "L" characters are appearing in IE 8. The problem is specifically occurring in the Healthcare Professionals section and the bottom two blocks of the page. Has anyone else experienced this or have ...

Guide to extracting the outcomes of a promise array and populating them into a new array using Protractor

I am facing a challenge with transferring data from an array of promises generated by the following code: element.all(by.repeater('unit in units')). It seems to be difficult for me to store this data into another array: element.all(by.repeater(& ...

Issue with onclick event not being triggered by Javascript function inside constructor

My current challenge involves implementing a function called makeHighlight within the SmartButton constructor. The purpose of this function is to execute whenever I click on the SmartButton object, which is represented by an image element. To achieve thi ...

An unexpected error has occurred: Uncaught promise rejection with the following message: Assertion error detected - The type provided is not a ComponentType and does not contain the 'ɵcmp' property

I encountered an issue in my Angular app where a link was directing to an external URL. When clicking on that link, I received the following error message in the console: ERROR Error: Uncaught (in promise): Error: ASSERTION ERROR: Type passed in is not Co ...

What is the best way to add multiple lines of text to a webpage using the span element?

Currently, I am developing a game that involves using a map, which consists of multiple lines. My question is whether it is possible to have the span tag cover multiple lines while ensuring that each line ends with a new line character. Below is an exampl ...

Accessing data in JSON format from a URL

I'm working on a website that analyzes data from the game Overwatch. There's this link () that, when visited, displays text in JSON format. Is there a way to use JavaScript to read this data and display it nicely within a <p> tag on my si ...

Capturing Vuejs data for various pathways

Currently, I am developing a Vue file that contains the following code: <router-link :to="{name: 'detailed'}" tag='li' @click='getData("test")'> testing</router-link> In the script section, the code looks like th ...

How can I create an Onclick function that works for multiple buttons sharing the same ID?

Having an issue with a component that loads data using buttons. I have a function that updates the state/variable based on the button ID, but since all button IDs are the same, it only works for the first button... I'm struggling to assign unique IDs ...

Having trouble removing a cookie in express?

Seems pretty straightforward. In the /user/login route, I set a cookie as shown below: if (rememberMe) { console.log('Login will be remembered.'); res.cookie('user', userObj, { signed: true, httpOnly: true, path: '/' ...

Request made to Ajax fetching complete webpage content

I have a page full of random tips at http://www.javaexperience.com/tips To display these tips on other pages of the website, I am using an ajax call to add the content returned by the call to a specific div's HTML. The code for the div is: <div ...

organize a data set using react's hook system

Trying to sort an array using react hooks but the state is not updating. Any help on what could be going wrong? import React, { useState } from "react"; import ReactDOM from "react-dom"; import "./styles.css"; const dogs = [{ name: "fido", age: 22 }, ...

What is the best way to find the longest element with the same class name using jQuery?

How can I dynamically find elements with the same length of class names? var className = $('.floor-4').attr('class').split(' ')[1]; var classLength = $('.' + className).length; Here is the HTML code: <div id="d ...

refreshing datatables with updated data from a different endpoint

Need help reloading datatables with the new ajax feature? I suspect it might be a scope issue. function refreshTable(tableName, src) { var table = $('#'+tableName).DataTable({ 'bProcessing': true, 'bServerSide ...

Issue with EventDrop and EventResize functionality in ROR4

I've got some js.coffee code located at http://pastebin.com/U3Mc8ZW6. This controller code can be found here: http://pastebin.com/chrYLga6 And here's the Model code: http://pastebin.com/n9fjt7ds Whenever I try to resize or drag an event, the d ...

The request is not functioning as expected for some reason

My current challenge involves retrieving photos from Instagram using a GET request. I attempted to use jQuery.get(), which has been successful for other types of GET requests but not for Instagram. Despite trying to switch to jQuery.getJSON(), the issue pe ...

How can I protect my jQuery script from being accessed by "FIREBUG"?

I was tasked with creating a jQuery script as follows: function DeleteFile(_FileID) { //ajax method to delete the file } The FileID is stored in the 'rel' attribute of the list. However, when I call "DeleteFile" from Firebug using the fileId ...