Sorting/Rearranging HTML elements using jQuery UI — A Small Guide With Example
This is a quick guide on how to sort or rearrange elements on an HTML page using the jQuery UI library. This task might seem tedious at first but is made super easy with jQuery.
Alright, first thing first. Get the CDN links for the jQuery & jQuery UI library from here & paste them inside the head tag on your HTML page. Easy!
I have also added the bootstrap link, but that is just for styling. You don’t have to add it.
Now, let us add some content on the page that we would like to rearrange or sort.
I will make a parent div with some children elements inside it. These children will then be sortable amongst themselves. Sibling divs are sortable amongst each other only. However, you can make elements from different parents merge together or sort amongst each other as well. That is something you can read about here and implement it yourself easily, I will keep this post small so I won't go into that here.
Considering that you want to sort only the divs from the same parent —
All the first-level children of one parent will be sortable amongst themselves. Similarly, all the first level ( just one level under — meaning, all children divs must be the same level inside the parent to be sortable amongst each other ) children of any other div will also be sortable amongst themselves only.
Now, In order to make the children divs sortable, all we need to do is call the builtIn function .sortable( ) on the parent element.
Call the function .sortable( ) on the parent div to make all children of it sortble/rearrangable.
Repeat this procedure on any other element that you would like to sort. Simply wrap the children divs inside a parent div and call the .sortable( ) function on it inside the script.
There are a lot of extra options that you can tweak to customize the behaviour of the library.
One such option is the placeholder. It allows you to style the placeholder or the position where the currently held div will be placed while you drag it. You add it by passing it as an object inside the .sortable( ) function & adding styles to it in the css.
Here is how it looks with the placeholder added —
That was all. You can do much more than this with the library. You can also merge children from different parents with some extra code.
This was a quick & short guide on how to sort or rearrange elements using jQuery. Let me know if it helped you in any way.
Thanks!