javascriptjquerygridstack

Gridstack dynamically created widgets are not dragging


I'm using GridStack library for creating a responsive layout for my widgets. Here is my function in which I'm creating widget on button click

function AddWidget()
    {
        var grid =  $('.grid-stack').data('gridstack');

        var html = '<div class="grid-stack-item-content">';
        html += '<div class="col-md-3"> <label> Sample Textbox </label></div>';
        html += '<div class="col-md-9"> <input type="text" class="form-control" /> </div>';
        html += '</div>';

        grid.addWidget($(html), 0, 0, 4, 1)
    }

Widget is creating successfully. I'm able to resize it too. But the problem is that they are not draggable. I can see ui-draggable class on my widget items html but they are not dragging.

If I already define widgets in my layout and then initialize stackgrid those are working fine.


Solution

  • Checkout the Gridstack float grid demo here http://gridstackjs.com/demo/float.html

    Adding another div fixes your issue - you need to have the div with class="grid-stack-item-content" nested inside another div. This top div will be initialised as the widget.

    For example:

    function AddWidget()
    {
        var grid =  $('.grid-stack').data('gridstack');
        var html = '<div>'
        html += '<div class="grid-stack-item-content">';
        html += '<div class="col-md-3"> <label> Sample Textbox </label></div>';
        html += '<div class="col-md-9"> <input type="text" class="form-control" /> </div>';
        html += '</div></div>';
    
        grid.addWidget($(html), 0, 0, 4, 1)
    }
    

    This fixes your issue and correctly add a widget you can now drag as normal. Hope that helps!