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:
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.
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/
Store the initial order as an array. Then sort by array index- the first one (A) will have array index 1, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With