Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort sibling <div>s with jQuery

I'm banging my head with the problem that has more to do with 2nd grade mathematics than programming. Here goes: four <div> elements are placed one after another, horizontally. When you click one, script places it in front. You click another one, and it's also placed in front, etc. You get the picture. Now, what I'd like to do is to sort remaining <div> elements (all but the first one) using original order.

Maybe this pic will make things clear:

enter image description here

After step #3, C should be placed after B, so it should go like this: D A B C.

Here's a sample code:

<html>
  <head>
    <title>mixit</title>
    <style type="text/css">
      .insidebox{
      width: 50px;
      height: 50px;
      line-height: 50px;
      margin: 0 0 0 20px;
      text-align: center;
      float: left;
      border: black solid 3px;
      font-family: sans-serif;
      cursor: pointer;
      }
    </style>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
    <script type="text/javascript">

    </script>
  </head>
  <body>
    <div id="container">
      <div id="a" class="insidebox">A</div>
      <div id="b" class="insidebox">B</div>
      <div id="c" class="insidebox">C</div>
      <div id="d" class="insidebox">D</div>
    </div>
  </body>
</html>

Now, I understand that I can use .insertAfter() to place element in front, but how should I tackle the sorting part? The keyword is initial order, not alphabetical order. Letters and boxes are given just for illustrative purposes.

like image 962
aL3xa Avatar asked May 07 '11 23:05

aL3xa


2 Answers

This should do what you want.

var $initial = $('.insidebox');
$('.insidebox').click(function(){
    var $this = $(this);

    $this.parent()
         .prepend($this)
         .append( $initial.not(this) );
});

You store the initial list and on each click re append it (excluding the current one)

demo http://jsfiddle.net/gaby/Dyafx/


update

Hell.. you do not even need to prepend the current element.. when you append the rest they will go after the clicked one anyway ..

var $initial = $('.insidebox');
$('.insidebox').click(function(){
    $(this).parent()
         .append( $initial.not(this) );
});

demo http://jsfiddle.net/gaby/Dyafx/1/

like image 121
Gabriele Petrioli Avatar answered Oct 23 '22 05:10

Gabriele Petrioli


Store the initial order as an array. Then sort by array index- the first one (A) will have array index 1, etc.

like image 37
Puppy Avatar answered Oct 23 '22 03:10

Puppy