I have a menu like this:
It's actually not that hard. JQuery almost gets you there by itself with the insertBefore and insertAfter methods.
function moveUp($item) {
$before = $item.prev();
$item.insertBefore($before);
}
function moveDown($item) {
$after = $item.next();
$item.insertAfter($after);
}
You could use these like
moveDown($('#menuAbout'));
and the menuAbout item would move down.
If you wanted to extend jQuery to include these methods, you would write it like this:
$.fn.moveUp = function() {
before = $(this).prev();
$(this).insertBefore(before);
};
$.fn.moveDown = function() {
after = $(this).next();
$(this).insertAfter(after);
};
and now you can call the functions like
$("#menuAbout").moveDown();
You can also use display: flex
on the parent then you can use order
function reset()
{
jQuery("#a").css("order", 10);
jQuery("#b").css("order", 20);
jQuery("#c").css("order", 30);
}
function reorder1()
{
jQuery("#a").css("order", 30);
jQuery("#b").css("order", 20);
jQuery("#c").css("order", 10);
}
function reorder2()
{
jQuery("#a").css("order", 30);
jQuery("#b").css("order", 10);
jQuery("#c").css("order", 20);
}
#main { display: flex; }
#a { color: red; }
#b { color: blue; }
#c { color: green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<div id="a">Foo</div>
<div id="b">Bar</div>
<div id="c">Baz</div>
</div>
<button onclick="reset()">Reset</button>
<button onclick="reorder1()">Reorder 1</button>
<button onclick="reorder2()">Reorder 2</button>
No native prototypal methods, but you can make one easily:
$.fn.moveDown = function() {
return this.each(function() {
var next = $(this).next();
if ( next.length ) {
$(next).after(this);
} else {
$(this).parent().append( this );
}
})
}
$('#menuAbout').moveDown().moveDown()
This uses jQuery.prototype.after