Isabela Cristina
Isabela Cristina

Reputation: 35

random css position jquery

using math.random, I can position the div to the left, randomly. But i need set the "left" and "right" positions randomly.

jQuery('#popup-container').css({'left' : (Math.floor(Math.random() * 15) + 3) + '%'})
<div id="popup-container" style="background:red;width:30px; height:30px;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Example, in attribute ".css({left", have an randon with "left or right". An array with these positions. how do I do that?

Upvotes: 0

Views: 407

Answers (1)

Aman Jain
Aman Jain

Reputation: 665

Simply make an array and push 'left' and 'right' into it.

var positions = [];
positions.push('left');
positions.push('right');

Now, use Math.random for selecting the index for positions array.

 jQuery('#popup-container').css(positions[Math.floor(Math.floor(Math.random()%2))], (Math.floor(Math.random() * 15) + 3) + '%')

Hope this helps.

Regards

Upvotes: 3

Related Questions