Randomly position div when loading page

3

I'm trying to make a div randomly position when loading page. I thought of the following, to make the margin-top and margin-left of div were random when loading the page, when loading again already displayed another margin, so div would have different position. How can I do to generate random numbers in margin ?

The scope follows:

<!DOCTYPE html>
<html lang="pt">
  <head>
    <style type="text/css">
        .bloco{
            background:blue;
            width:100px;
            height:100px;
        }

    </style>

  </head>
  <body>
    <div class="bloco">

    </div>    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script><script>$(document).ready(function(){$(".bloco").css({'margin-top',' ' , 'margin-left', ' '})//<-- colocar aqui margin top e left de forma randomica 
                                                                        //ao carregar pagina
            });     
    </script>   
  </body>
</html>
    
asked by anonymous 02.01.2017 / 13:43

2 answers

3

Use Math.random to do this:

$(".bloco").css({
      marginLeft: (Math.random() * 1000),
      marginTop:  (Math.random() * 1000)
})

Note: I put the multiplication by 1000, because Math.random generates a random number of 0 to 1 .

If you want to consider putting the values of margin-left or margin-top within window size limits, you can use Math.min to prevent it from exceeding size:

See:

 {
    marginLeft: Math.min($(window).width(), Math.random() * 1000)
    marginTop: Math.min($(window).height(), Math.random() * 1000)
 }

In this case, the value generated for margin-left would always be equal to or less than the size of the window. This is because Math.min always returns the smallest value passed by argument.

References:

02.01.2017 / 13:47
5

You can do this, in order to ensure that you will never leave the document (body):

$(document).ready(function(){
  const m_top = Math.floor((Math.random() * $('body').height()) + 1);
  const m_left = Math.floor((Math.random() * $('body').width()) + 1);
  $(".bloco").css({
    'margin-top': m_top+ 'px',
    'margin-left':m_left+ 'px'
  });
});
.bloco{
            background:blue;
            width:100px;
            height:100px;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="bloco">

    </div>  
    
02.01.2017 / 13:50