dSquared
dSquared

Reputation: 9825

Optimal Method of Changing Order of Elements using jQuery

Given the following:

<a id="moveElementUp">Move Up</a>
<a id="moveElementDown">Move Dowm</a>

<div id="elementHolder">
    <a id="element-1">1</a>
    <a id="element-2">2</a>
    <a id="element-3">3</a>
    <a id="element-4">4</a>
</div>

<script type="text/javascript">
    function reOrder (el){
        // Change IDs of Elements to be Sequential
    }
    $('#moveElementUp').click(function(e){
        // Move Clicked Element Up One Spot in List

        reOrder();
    });
    $('#moveElementDown').click(function(e){
        // Move Clicked Element Down One Spot in List

        reOrder();
    });
</script>

What is the optimal (and fastest) way of going about changing the order of the elements and changing the IDs of all elements to maintain sequential order using jQuery?

Any help would be greatly appreciated!

Upvotes: 3

Views: 1892

Answers (1)

Blazemonger
Blazemonger

Reputation: 92903

This will let you rearrange items arbitrarily. However, it will remove the spaces between the anchor tags. You can solve this by adding spaces between the anchor tags (as I did here: http://jsfiddle.net/FqwDc/1/ ), or by using nested divs instead.

var $sel; // anchor last clicked on
var prefixstr = "element-";

$('a[id^="'+prefixstr+'"]').click(function(e) {
    $sel = $(this);
});
$('#moveElementUp').click(function(e) {
    // Move Clicked Element Up One Spot in List
    $sel.prev().before($sel);
    changeIDs($('#elementHolder'));
});
$('#moveElementDown').click(function(e) {
    // Move Clicked Element Down One Spot in List
    $sel.next().after($sel);
    changeIDs($('#elementHolder'));
});

function changeIDs($j) { // renumber the IDs
    $j.children('a').each(function(i) {
        $(this).attr('id',prefixstr+i);
    });
}

Upvotes: 2

Related Questions