Search code examples
javascriptpluginssortablejs

How to customize the cursor on the SortableJS plugin when drag an item


I need help please ! :D I can't find how to change the cursor when dragging with the "SortableJS" plugin (SortableJS).

I use the plugin without react, the basic one in a table to move the rows.

Thanks in advance ! :D


Solution

  • For the ones that fall here from G like me, something like this will do it:

    var grid = document.getElementById('grid');
    new Sortable(grid, {
        animation: 150,
        swap: true,
        swapThreshold: 0.65,
        ghostClass: 'dragFrom',
        swapClass: 'dragTo',
        forceFallback: true, // This is it!
        onChoose: function(e) {
            e.target.classList.add('grabbing');
        },
        onUnchoose: function(e) {
            e.target.classList.remove('grabbing');
        },
        onStart: function(e) {
            e.target.classList.add('grabbing');
        },
        onEnd: function(e) {
            e.target.classList.remove('grabbing');
        },
      onMove: function(e) {
            e.target.classList.add('grabbing');
        },
    });
    .grabbing * {
        cursor: grabbing !important;
    }
    .grid {
      margin:0;
      padding:0;
    }
    .grid-square {
      margin:5px;
        display: inline-block;
        background-color: #fff;
        border: solid 1px rgb(0,0,0,0.2);
        text-align: center;
        cursor: grab;
      padding-top:35px;
      width:75px;
      height:50px;
    }
    .grid-square:active {
        cursor: grabbing!important;/* fighting on all fronts */
    }
    .dragFrom{
        background-color: #48b4e6!important;
    }
    
    .dragTo {
        background-color: #30ec5f!important;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.0/Sortable.min.js"></script>
     
    <div id="grid">
        <div class="grid-square">1</div>
        <div class="grid-square">2</div>
        <div class="grid-square">3</div>
        <div class="grid-square">4</div>
        <div class="grid-square">5</div>
        <div class="grid-square">6</div>
    </div>

    The forceFallback: true, line is the key to bypass the issue pointed by Arthur in his comment to the question post.

    The onChoose, onUnchoose, onStart, onEnd and most CSS are my dirty solution after testing some times. Hope this helps someone.