Requirements
- boxes are hidden until whole page loads
- boxes are set to random positions around browser view port
- boxes need to animate to their proper positions
You can store the original position and after your random placement start animating them to go back to their starting position. I also cached any DOM reference which were repeated to speed up the code execution (most likely not noticeably but it's good practice)
DEMO - Boxes placed at random and then animated back to their proper positions.
I have separated the 2 actions, placing the boxes at random locations using your original code but now also storing the original position in associated data using jQuery's Data which is then used to animate them back to their proper positions.
You can now randomise and re-set the boxes on demand by calling either method:
$(document).ready(function() {
var h = $(window).height();
var w = $(window).width();
var $allBoxes = $('#intro .box');
placeBoxesRandomly($allBoxes, h, w);
placeBoxesToDataStorePositions($allBoxes);
});
placeBoxesRandomly
still does what it did before except it now also associates the original starting position data with the elements:
function placeBoxesRandomly($boxes, h, w) {
$boxes.each(function() {
var $box = $(this);
var position = $box.position();
tLeft = w - Math.floor(Math.random() * 900), tTop = h - Math.floor(Math.random() * 900);
$box.css({
"left": tLeft,
"top": tTop
});
$box.data("start-position-left", position.left);
$box.data("start-position-top", position.top);
});
}
placeBoxesToDataStorePositions
places the boxes to the positions stored in the associated data.
function placeBoxesToDataStorePositions($boxes) {
$boxes.each(function() {
var $box = $(this);
$box.animate({
"left": $box.data("start-position-left"),
"top": $box.data("start-position-top")
}, 3000);
});
}