I’m making an abacus with 10 beads in it. When a bead is clicked that bead and all the beads before it are arranged left in the abacus, and the remaining beads are moved to the right in the abacus.
The list:
<ul class="abacus">
<li class="bead">1</li>
<li class="bead">2</li>
<li class="bead">3</li>
<li class="bead">4</li>
<li class="bead">5</li>
<li class="bead">6</li>
<li class="bead selected">7</li>
<li class="bead off">8</li>
<li class="bead off">9</li>
<li class="bead off">10</li>
</ul>
The CSS:
li.bead {
cursor: pointer;
width: 28px;
height: 32px;
float: left;
}
/* just for visuals: */
li.bead.selected {
background-image: url('../images/smartie-selected.png');
}
li.bead.off {
float: right;
background-image: url('../images/smartie-unselect.png');
}
Because the ‘off’ beads are floating to the right, their order has to be reversed (otherwise the abacus will look like: [1][2][3][4][5][6][7]——–[10][9][8]).
The jQuery I’m using for this is:
$("li.bead").click(function() {
// remove the 'selected' class of the previously selected bead (just for visuals):
$("li.bead.selected").removeClass("selected");
// save the number of the bead was selected:
var no = Number($(this).html());
// add the 'selected' class to the clicked bead (just for visuals):
$(this).addClass("selected");
// add the 'off' class to all the 'higher' beads than the selected one
// and removing that class for all he lower beads:
$(this).parent().children().each(function() {
if(Number($(this).html()) > no) {
$(this).addClass('off');
} else {
$(this).removeClass('off');
}
});
// reverse all beads:
$(this).parent().children().each(function(i, li) {
$(this).parent().prepend(li);
});
});
So, the last step in that jQuery reverses all beads, which correctly arranges the ‘off’-beads, but also reverses the other beads, making the abacus look like, for instance:
[4][3][2][1]————[5][6][7][8][9][10]
What should I add to only reverse the first beads back?
I would aim to avoid the float. First I would try adding a margin-right value to the selected element. Something like this…
and CSS…
Here is a working example
if you need the right margin to be dynamic you could always calculate it in javascript and add it to the selected element, something like…