Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Randomize boxes and animate them on window load

On the picture bellow is what I'm trying to build: random boxes

Idea is that all the boxes are hidden until whole page loads. Then they should have set random positions around browser view port and then they (boxes) needs to be animated to move to their proper positions.

Boxes have absolute positions in CSS, and my idea is when windows loads to put initial position in variable, then randomize position of the box, and then finally move it to the starting position. Hope I'm clear :)

Here is my current setup: http://jsfiddle.net/HgMB4/

You will notice that I'm missing code on window load, because I'm not sure how to animate boxes to their initial position.

$(window).load(function(){
    //Huh! What to write here to animate boxes to their initial positions set by CSS?
});
like image 374
RhymeGuy Avatar asked May 11 '26 03:05

RhymeGuy


1 Answers

Try this

    $(document).ready(function(){
      var h = $(window).height();
      var w = $(window).width();            
      $('#intro .box').each(function(){
            var originalOffset = $(this).position(),
            $this = $(this),
            tLeft = w-Math.floor(Math.random()*900),
            tTop  = h-Math.floor(Math.random()*900);

           $(this).animate({"left": tLeft , "top": tTop},5000,function(){
                           $this.animate({
                               "left": originalOffset.left, 
                               "top": originalOffset.top
                           },5000);

                        });        
    });
});
​

This will animate the boxes to random position and then will move them back to their original position.

Here is the working demo http://jsfiddle.net/HgMB4/18

If you want to animate boxes only when they move to initial position then try this

$(document).ready(function(){
    var h = $(window).height();
    var w = $(window).width();            
    $('#intro .box').each(function(){
        var originalOffset = $(this).position(),
            $this = $(this),
           tLeft = w-Math.floor(Math.random()*900),
           tTop  = h-Math.floor(Math.random()*900);

        $(this).css({
            "left": tLeft,
            "top": tTop
        });

        $this.animate({ "left": originalOffset.left, 
                         "top": originalOffset.top
                     },5000);

    });
});
​
​

Here is the working demo http://jsfiddle.net/HgMB4/22

like image 52
Sanjeev Avatar answered May 14 '26 01:05

Sanjeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!