glassraven
glassraven

Reputation: 323

Jquery: animate element randomly on click

I wonder if I can animate elements on click randomly. I have this code:

$('.div').click(function(){
       if( $(this).hasClass('active')){
           var divAnim=$(this).animate({bottom:'+=600', left:'+=600'},1000);
           var rand=Math.floor(Math.random() * divAnim);
           rand;
       }
       return true;

  });

But the result is the same without the line "Math Random". Is it possible to achieve a random animation that changes the default values?

Upvotes: 0

Views: 1594

Answers (2)

Yolo
Yolo

Reputation: 1579

Here is an example snippet of jquery site. Note the CSS part. Your div container needs an absolute position so it knows where to start from.

function makeNewPosition(){
    
    // Get viewport dimensions (remove the dimension of the div)
    var h = $('#block_wrapper').height() - 50;
    var w = $('#block_wrapper').width() - 50;
    
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    
    return [nh,nw];    
    
}
$( "#go" ).click(function() {

  var pos = makeNewPosition();
  $('#block').animate({ top: pos[0], left: pos[1] });
  
});
#block_wrapper {
    position: relative;
    width:600px;
    height:400px;
    background:#f4f4f4;
  }
  #block {
    position: absolute;
    background-color: #abc;
    left: 50px;
    width: 50px;
    height: 50px;
    margin: 5px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="go">&raquo; Run</button>
<div id="block_wrapper">
<div id="block">Hello!</div>
</div>

UPDATED SNIPPED ABOVE

Upvotes: 1

Harry
Harry

Reputation: 4050

How about this? (P.s typing on my phone)

 $('.div').click(function(){
   if( $(this).hasClass('active')){

 var randomHeight= Math.floor(Math.random() * $(window).height());


 var randomWidth= Math.floor(Math.random() * $(window).width());


       $(this).animate({bottom: randomHeight, left:     randomWidth},1000);

   }
   return true;

  });

Upvotes: 1

Related Questions