Can anyone show me how to generate div elements in a loop using jQuery and change their position with the "mouseover" function? I've tried some code, but the positioning isn't changing correctly. Any suggestions on what needs fixing?
var r, g, b, counter, i;
//generate random number between 20 and number.
function generateRandomNumber(number) {
return Math.floor(Math.random() * (number - 20)) + 20;
}
// maximum number of random elements is 30.
counter = generateRandomNumber(30);
for (i = 0; i < counter; i++) {
var div = $("<div/>");
div.id = "randomlyPlaced" + i;
//random style for the elements
r = generateRandomNumber(255);
g = generateRandomNumber(255);
b = generateRandomNumber(255);
$(div).css({
position: "absolute",
background: "rgb(" + r + "," + g + "," + b + ")",
height: generateRandomNumber(200) + "px",
width: generateRandomNumber(400) + "px",
top: generateRandomNumber(500) + "px",
left: generateRandomNumber(1000) + "px"
});
//append the elements to body.
$('body').append(div);
//change the position of the element.
$("#" + div.id).mouseover(function() {
$(this).animate({
top: generateRandomNumber(500) + "px",
left: generateRandomNumber(1000)
}, 500, "linear");
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Randomly Placed Animated rectangles</title>
</head>
<body style="width: 80%; height: 80%; background-color :rgb(164, 173,
226); position:relative;">
<div id='+div.id+'></div>
</body>
</html>