Move the square by Atinux
Move the square is just a test with jQuery by Atinux.
by Atinux
HTML
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="help">
Clic on a square to move the grey square on it.<br/>
Duration : <input type="text" name="duration" id="duration" value="400" />
</div>
CSS
.square {
background-color: rgb(240,240,240);
width: 100px;
height: 100px;
float: left;
margin: 10px;
margin-right: 0;
cursor: pointer;
}
.square:hover {
background-color: rgb(230,230,230);
}
.grey-square {
width: 100%;
height: 100%;
display: inline-block;
background-color: rgb(200,200,200);
}
.grey-square.hide {
width: 0;
}
.help {
color: grey;
clear: left;
padding: 5px;
padding-left: 10px;
border-top: 1px rgb(220,220,220) solid;
height: 300px;
background: -webkit-linear-gradient(whitesmoke, white);
font-family: 'Trebuchet MS', Verdana, sans-serif;
text-shadow: 1px 1px 1px rgb(210,210,210);
line-height: 27px;
}
.help input[type="text"] {
border: 1px rgb(200,200,200) solid;
padding: 3px;
width: 50px;
text-align:center;
color: rgb(120, 120, 120);
border-radius: 3px;
}
.help input[type="text"]:focus, .help input[type="text"]:hover {
border-color: rgb(170,170,170);
outline: none;
color: rgb(80,80,80);
}
JavaScript
var app = {
actualSquare: 0,
elActualSquare: null,
nbSquare: 0,
isAnimating: false,
init: function() {
var that = this,
square;
$('.square').each(function(i, el) {
square = $(el);
square.html($('<div>', {
'class': 'grey-square' + (i ? ' hide' : '')
}));
square.click(function(e) {
that.moveGreySquare(square, i);
});
that.nbSquare++;
if (!i) {
that.elActualSquare = square;
}
});
},
moveGreySquare: function(square, i) {
if (i !== this.actualSquare) {
var diff = Math.abs(this.actualSquare - i),
direction = (i > this.actualSquare ? 'right' : 'left'),
duration = parseInt($('#duration').val(), 10);
duration = (isNaN(duration) ? 0 : duration);
duration = Math.round(duration / diff);
if (!this.isAnimating) {
this.isAnimating = true;
this.moveToNextSquare(direction, duration, i);
}
}
},
moveToNextSquare: function(direction, duration, finishSquare) {
var invDirection = (direction === 'right' ? 'left' : 'right'),
incr = (direction === 'right' ? 1 : -1),
that = this,
called = false,
nextSquare;
if (this.actualSquare !== finishSquare && ((this.actualSquare > 0 && direction === 'left') || (this.actualSquare + 1 < this.nbSquare && direction === 'right'))) {
this.elActualSquare.css('text-align', direction);
nextSquare = (direction === 'right' ? this.elActualSquare.next() : this.elActualSquare.prev());
nextSquare.css('text-align', invDirection);
$('.grey-square', this.elActualSquare).animate({
'width': 0
}, duration);
$('.grey-square', nextSquare).animate({
...