javascriptjquerysortablejs

SortableJS Next and Previous Buttons don't call OnEnd function


I use the SortableJS library (SortableJS/Sortable) to reorder pictures. I placed buttons: Next and Previous on each pictures to facilitate movement in desktop mode.

The buttons work well but the problem is that the SortableJS: OnEnd function (which manages the processing of the indexes: oldIndex and newIndex) is not executed.

How can I make my buttons work so that sortableJS can get the new indexes to organize the photos?

Here is my code

<div class="pictures">
<div class="picture-item">
    <img src="...mypicture.jpg...">
    <div class="btn-nav">
        <button type="button" class="sort-prev">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="arrow-left-circle" viewBox="0 0 16 16">
                <path fill-rule="evenodd" d="M1 8a7 7 0 1 0 14 0A7 7 0 0 0 1 8zm15 0A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-4.5-.5a.5.5 0 0 1 0 1H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5H11.5z"/>
            </svg>
        </button>
        <button type="button" class="sort-next">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="arrow-right-circle" viewBox="0 0 16 16">
                <path fill-rule="evenodd" d="M1 8a7 7 0 1 0 14 0A7 7 0 0 0 1 8zm15 0A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM4.5 7.5a.5.5 0 0 0 0 1h5.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3a.5.5 0 0 0 0-.708l-3-3a.5.5 0 1 0-.708.708L10.293 7.5H4.5z"/>
            </svg>
        </button>
    </div>
</div>
...
</div>

// Array populated from dropzoneJS upload
var pictures = [{filename:test.jpg, position:0},{filename:test2.jpg, position:1}, ...]

var sortable = new Sortable(document.getElementById('pictures'), {
    onEnd:function(evt)
    {
       // Function work with drag and drop not button click !
        console.log(pictures);

        let oldIndex = evt.oldIndex,
            newIndex = evt.newIndex;

        pictures.splice(newIndex, 0, pictures.splice(oldIndex, 1)[0]);
        pictures.forEach((picture, index) => picture.position = index);
        updateHiddenField(pictures);
    }
});

$(document).on('click', '.sort-prev', function(){
    var current = $(this).closest('.picture-item');
    current.prev().before(current);
});

$(document).on('click', '.sort-next', function(){
    var current = $(this).closest('.picture-item');
    current.next().after(current);
});

Solution

  • As you can see, onEnd callback receives Event as a parameter. In this case you should call onEnd by yourself and pass the data you use in your onEnd method like this:

     data = {
      oldIndex: 0, // just for example
      newIndex: 1
    }
    
     $(this).options.onEnd(data)
    

    ;