I want a user to be able to reorder a list on a click event. Here is my code:
$(function() {
$('#reOrder li').each(function, (index) {
$(this).attr('id', index);
});
$("#reOrder").delegate("li", "click", function() {
var $indexItem = $(this).index('#reOrder li');
var $thisTxt = $(this).text();
var $prevTxt = $(this).prev('li').text();
$($thisTxt).replaceWith($prevTxt);
//alert($thisTxt);
//alert($prevTxt);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="reOrder">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
So in this example I would like to move the clicked li item and its contents to the position above in the DOM. I suppose strictly speaking it is being moved down in the index of li items.
This is going to be extended later to include buttons that move li items up and down and a submit button that saves the order/state of the list items.
I have found a lot of info on drag and drop (which is not required) but not much on this sort of functionality.
Something you might want to check out is the jQuery UI sortable
If you simply want to move items around by clicking etc. have a look at the following methods:
detach function
DOM insertion functions
Detach will allow you to remove the clicked element from the DOM and will have a copy available, you can then reinsert in the desired position using one of the DOM insertion functions.