📜 ⬆️ ⬇️

Adding sorting animation to jQuery UI

I understand, perhaps, there is a feeling that the article was late for the year by 2, now it is fashionable to write about es6, react, redux or other fashionable things in the world of frontend.

However, I think many still have projects that use jQuery + jQuery UI. And in one of the projects, using jQuery UI for sorting the list items, I needed a sorting animation, which in jQuery UI is not out of the box. Googling and stackoverflow search only led to strange solutions through standard jquery-ui callbacks, and since there were several places where sorting was used, such solutions did not suit me.

In addition, the project used the jQuery UI Touch Punch library, which allows for an elegant way to force jQuery UI to work on touch devices, I thought, why not do the same.

Having begun to understand how sortable works, it became clear that when sorting the elements that are being dragged and in which place we want to put it, simply change places in the DOM tree. In this situation, of the possible implementations of my task, only one idea came to mind.
')
After the element has been moved to a new place in the DOM tree, depending on the sorting direction, move it in the opposite direction to its height (or width, depending on the axis of the sorting direction) and immediately start the animation. Perhaps the diagram will be a little clearer:



Consider each step:

  1. the user starts dragging Item 4 into Item 3 ;
  2. jQuery UI sorting works in native ways;
  3. the plugin shifts the element using the translateY transformation back to its old position, without changing the position of the element in the DOM tree;
  4. immediately starts the animation through css-transition.

Voila, without affecting the basic logic of the sortable widget, we added animation to it. I implemented it as a sortable widget extension, so to add animation to an existing project that uses sortable, you just need to connect the script and add the animation property to the sortable parameters:

<script src="jquery.ui.sortable-animation.js"></script> <script> $('#sortable').sortable({ // ... //    axis: 'y', //  ( 'x',  'y'),      animation: 200, //   (0 -   ) }); </script> 

GitHub source code
Demo

Pros:



And, of course, cons:



At the moment, the library solves its problems, but it would be nice, at least, to get rid of the necessity of specifying the axis property. If you have ideas and time, pool requests are welcome.

Source: https://habr.com/ru/post/273923/


All Articles