Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Move element position

In each div, there are two buttons: higher and lower. When 'higher' is clicked, if this div is not at the top position, then it is moved higher than original. When 'lower' is clicked, then the element will be moved lower than original.

The question is: How to the elements can be moved up and down of with respect 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>
like image 400
mlzboy Avatar asked Feb 21 '26 01:02

mlzboy


1 Answers

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

With insertAfter and insertBefore we 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;
});
like image 81
Yi Jiang Avatar answered Feb 23 '26 14:02

Yi Jiang