jquery – Randomly place div when loading page

Question:

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

Here's the scope:

<!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>

Answer:

You can do this in order to ensure that it 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>

<div class="bloco">

    </div>  
Scroll to Top