0

I have two panels, one on the left and another one on the right side. There are many spans in the left panel. When user clicks on any span in the left panel, I move them to right panel using the following code:

$(".left-panel span").click(function(){
    $(".right-panel").append(this);
});

Everything is OK, just If user clicks on the 5th span first, then clicks on 2nd span, I want the 2nd span to be before 5th span.

I want the spans to move with same other in the left panel.

Note: Please do not suggest to use jQuery.prepend() function. Think about other spans too.

5
  • 1
    This question could be helpful in terms of inserting spans into right-panel and then reordering them based on some condition Commented Mar 11, 2014 at 20:30
  • are there any on the right to begin with? Commented Mar 11, 2014 at 20:32
  • @Freak_Droid So insert before what? Commented Mar 11, 2014 at 20:33
  • @andrew assume that there is 5th span on the right side and now we want insert the 2nd one. Commented Mar 11, 2014 at 20:34
  • @ArtyomNeustroev Nice! that did the job. Commented Mar 11, 2014 at 20:46

2 Answers 2

2

First store a data variable with each span to indicate it's original position. Then use .sort() to sort the spans based on the index:

jsFiddle Demo

$(".left-panel span").each(function(){
   $(this).data('sort', $(this).index()); 
});

$(".left-panel span").click(function(){
    $(".right-panel").append(this);

    $('.right-panel span').sort(function(a, b){
        return $(a).data('sort') > $(b).data('sort');
    }).appendTo($('.right-panel'));
});

As KevinB points out in the comments. jQuery's .sort() is not documented and so if you prefer you can use the native Javascript Array.prototype.sort().

Sign up to request clarification or add additional context in comments.

2 Comments

it might not be as pretty, but i'd suggest using Array.prototype.sort instead, just in case $.fn.sort is removed one day (it isn't documented.) jsfiddle.net/saS5R/2
Good point, added your demo to the answer (hope you don't mind) :)
-1

i think you have to add a filed to the panel. or use other filed of their sequence

<span sort_id="1" ..../〉  ..

then you need loop all panel on right to get the max or min sort_id or the closest sort_id

at last you can use insertBefore() or insertAfter() to add this panel

3 Comments

This methods needs a lot of loops through DOM elements
Dont use arbitrary attributes, use data: stackoverflow.com/questions/8225918/…
it just a example. we need know how to sort them or their original sequence. this will be less calculation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.