JQuery: moving item position

Each div has two buttons: above and below. When "higher" is pressed, if this div is not in the upper position, it moves above the original. When the "lower" button is pressed, the item will be moved below the original.

The question arises: how can elements move up and down relative to another element?

<div>
    <div id="a1">a1<input name='higher' type='button' value='higher'/><input name='lower' type='button' value='lower'/></div>
    <div id="a2">a2<input name='higher' type='button' value='higher'/><input name='lower' type='button' value='lower'/></div>
    <div id="a3">a3<input name='higher' type='button' value='higher'/><input name='lower' type='button' value='lower'/></div>
</div>
+3
source share
2 answers

You can try something like this: http://www.jsfiddle.net/yijiang/hwPPP/

With insertAfterand insertBeforewe can move the parent of the buttons up and down.

$('#list').delegate('input[type="button"]', 'click', function() {
    var parent = $(this).parent();

    if(this.value === 'higher'){
        parent.insertBefore(parent.prev());
    } else {
        parent.insertAfter(parent.next());
    }

    return false;
});
+6
source

Maybe you should check out something like JqueryUI Sortable:

http://jqueryui.com/demos/sortable/

next()/previous() insertBefore()/insertAfter() jquery :

$("#a1").insertAfter($('#a1').next());
+1

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


All Articles