Search code examples
javascriptgridstack

How to get the new y-value within gridstack.js


I'm using Gridstack for draggable div's. How do I get the new value of data-gs-y (so to which y-axis the div was dropped). Actually I tried this:

<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="grid-stack" data-gs-width="12" data-gs-animate="yes">
                    <div class="grid-stack-item" data-gs-x="0" data-gs-y="0" data-gs-width="12" data-gs-height="1" data-gs-id="facebook">
                        <div class="grid-stack-item-content">facebook</div>
                    </div>
                    <div class="grid-stack-item" data-gs-x="0" data-gs-y="1" data-gs-width="12" data-gs-height="1" data-gs-id="workbook">
                        <div class="grid-stack-item-content">workbook</div>
                    </div>
                    <div class="grid-stack-item" data-gs-x="0" data-gs-y="2" data-gs-width="12" data-gs-height="1" data-gs-id="pictures">
                        <div class="grid-stack-item-content">pictures</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    $(function () {
        $('.grid-stack').gridstack({
            disableResize: true,
            removable: true
        });
    });

    $('.grid-stack').on('dragstop', function(event, ui) {
            var element = event.target;
            var id = $(element).attr('data-gs-id');
            var y = $(element).attr('data-gs-y');
            alert(id + y);
        });

    $('.grid-stack').on('dropped', function (event, previousWidget, newWidget) {
        alert('dropped'); // It's not thrown
    });

    $('.grid-stack').on('change', function(event, items) {
        var element = items[0].el[0];
        var id = $(element).attr('data-gs-id');
        var y = $(element).attr('data-gs-y');
        alert(id + y);
    });
</script>

So the event dragstop and also change is given me the current/old value of the y-axis and the dropped event is not thrown..

How do I get the new value of the y-axis?


Solution

  • I think you can use "mutation observer" to listen changes to the attribute 'data-gs-y' on each div element. I wrote following code and verified on this demo http://gridstackjs.com/demo/knockout.html

    var divs = document.querySelectorAll(".grid-stack-item");
    var dragging = false;
    divs.forEach(function(div){
     const observer = new MutationObserver((mutations) => { 
       mutations.forEach((mutation) => {
         if(!dragging){
           alert("new y-value " + div.getAttribute("data-gs-y"));
         }
       });
     });
    observer.observe(div, { attributes: true, attributeFilter: ['data-gs-y'] });
    
    div.onmousedown = function(){ dragging = true;}
    div.onmouseup = function(){ dragging = false;}   
    });