Randomly position div when loading page

Asked

Viewed 609 times

3

I’m trying to get a div is randomly positioned when loading a page. I thought the following, make the margin-top and margin-left of div were random when loading the page, when clicking again showed another margin, so the div would have different position. How can I generate random numbers in margin?

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

2 answers

5

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

  • Thank you very much for your reply

3


Use Math.random to do this:

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

Note: I put the multiple per 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 the limits of window size, you can use Math.min, to prevent it from oversize:

Behold:

 {
    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 window size. This is because Math.min always returns the smallest value passed by argument.

References:

  • Thank you very much man, it worked

Browser other questions tagged

You are not signed in. Login or sign up in order to post.