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

Animating the height with jQuery can result in the background color being overlooked

For those curious about the issue, check out the JSFiddle. There seems to be an anomaly where the background of the <ul> element disappears after the animation on the second click. Oddly enough, even though Firebug shows that the CSS style is being a ...

The call to C# Web Api is not being triggered by jQuery

While attempting to make a POST request to a web API using jQuery script, I am encountering an issue where the data doesn't bind correctly and the Page parameter shows up as null. jQuery $("document").ready(function(){ myTimer= setInterval( "Sta ...

Encountering issues with installing Angular using npm due to errors

When I run npm install, I encounter errors. Though I can get it to work by using npm install --force, I prefer not to rely on the force flag. After reading through the errors, it seems like there might be a version compatibility issue, but I'm having ...

Select a random character from a string using JavaScript

This question sets itself apart from Removing random letters from a string as it focuses on selecting a random letter from a string in JavaScript without removing any characters. The goal is to implement a code that picks random letters from a string in J ...

Modifying the appearance of select components in React MUI using CSS

Can someone help me modify the appearance of the react material UI select component to match this design: I have already applied the following CSS styling: const styles = { width:'250px', border:'1px solid gray', borderBot ...

What is the proper way to utilize setTimeout in TypeScript?

Let's take a look at an example of how to use setTimeout in Angular and TypeScript: let timer: number = setTimeout(() => { }, 2000); However, upon compilation, you may encounter the following error message: Error TS2322: Type 'Timeout' ...

How to eliminate query strings from the current page's URL using JavaScript

Looking for a way to remove the querystring from the current page URL using JavaScript when a button is clicked. Can someone please provide the necessary code for this? ...

My jQuery does not function correctly when I try to set a variable

Presented below is a crucial function: <script type='text/javascript'> $('#clicktogohome').live('click', function(){ history.pushState({}, '', this.href); popstate(this.href); return false; }); $('# ...

Exploring the capabilities of rowGroup within DataTables

Currently, in the process of completing a project, I am retrieving data from a REST API to populate my DataTable. To avoid displaying duplicate items, I am interested in creating subrows in the DataTable with a drop-down menu based on an item in the "Deliv ...

Notifying a Child Component in React When a Props-Using Function Resolves a REST Call

When I submit an item or problem, I trigger a function in the parent component that has been passed down to the child component as props. After sending my information, I want to clear the input fields. The issue is that I am clearing the input fields immed ...

Enclosing values in JavaScript literals

I apologize for the inconvenience. I am unsure why it is not functioning properly. If I input <button type="button" onclick="document.getElementById("demo").innerHTML = Date()">click</button> the above code does not work. However, if I u ...

pre-iframe loading function

Is it possible to capture the state of an iframe while data is loading? The onload event only fires once all content has finished loading. I would appreciate any assistance with this issue. Thank you. ...

Class for making elements draggable using jQuery UI

Is it possible to use jQueryui's draggable/droppable combo and add a class to the dragged item when dropped into a specific container, rather than adding a class to the container itself? I've tried adding a class to the container, but that is not ...

AngularJS: Utilizing $http to fetch XML data instead of JSON

Looking to extract data from a website using angularjs / javascript. I am familiar with the $http object in angularjs which can make get requests. I have used it before to retrieve json, but I'm wondering if I can use it for XML (HTML) as well? (I th ...

What are the reasons and methods for cleaning up components in React JavaScript?

While I comprehend the necessity of tidying up our components in React to avoid memory leaks (among other reasons), as well as knowing how to utilize comonentWillUnmount (which is outdated) and the useEffect hook, my burning question remains: what exactl ...

Is it feasible to utilize math.max with an array of objects?

When it comes to finding the largest number in an array, solutions like this are commonly used: var arr = [1, 2, 3]; var max = Math.max(...arr); But how can we achieve a similar result for an array of objects, each containing a 'number' field? ...

What is preventing me from executing these two jQuery functions?

I'm attempting to implement this in jQuery, but I'm encountering an issue. The two click functions work separately, but not together. Why is this happening and what can I do to resolve it? $("p").click(function(){ $(this).addClass("test"); }) ...

How can I eliminate the default background of Mui tooltip and personalize it in react?

Below is an example of how to customize a nested tooltip within a default background tooltip in MUI. The challenge here is to remove the grey border in the customized tooltip and have only a white background with black text. Check out the code snippet be ...

Having trouble with Firefox not displaying the image source with an absolute path

ASP.NET Application I am experiencing some confusion with displaying images. While Internet Explorer shows the images correctly, Firefox is not showing them on the production server. The image url generated on the server is: \chartings\charts& ...

Avoiding external variable reference through Jest.mock

For snapshot testing, I need to create a simple dummy mock of 1 react component. When attempting to use React.Component within the mock function, an error is thrown: The second argument of jest.mock() cannot reference external variables. However, usin ...