KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I'm trying to make Divs to appear randomly anywhere on a webpage with javascript. So a div appears then disappears, then another div appears somewhere else on the page then disappears, then another div appears again in another random spot on the page then disappears, and so on. I'm not sure on how to generate random units in pixels or what technique to use to generate random positions. How do I do that? Here's my code: var currentDivPosition = myDiv.offset(), myDivWidth = myDiv.width(), myDivHeight = myDiv.height(), var myDiv = $('<div>'), finalDivPositionTop, finalDivPositionLeft; myDiv.attr({ id: 'myDivId', class: 'myDivClass' }); // already defined with position: absolute is CSS file. // Set new position finalDivPositionTop = currentDivPosition.top + Math.floor( Math.random() * 100 ); finalDivPositionLeft = currentDivPosition.left + Math.floor( Math.random() * 100 ); myDiv.css({ // Set div position top: finalDivPositionTop, left: finalDivPositionLeft }); $('body').append(myDiv); myDiv.text('My position is: ' + finalDivPositionTop + ', ' + finalDivPositionLeft); myDiv.fadeIn(500); setTimeout(function(){ myDiv.fadeOut(500); myDiv.remove(); }, 3000);
Tags (comma-separated)
Save Edits
Cancel