Reputation: 77
I'm looking for a way to randomly position a div anywhere on a page (ONCE per load).
I'm currently programming a PHP-based fantasy pet simulation game. One of the uncommon items on the game is a "Four Leaf Clover." Currently, users gain "Four Leaf Clovers" through random distribution - but I would like to change that (it's not interactive enough!).
What I Am Trying To Do:
The idea is to make users search for these "Four Leaf Clovers" by randomly placing this image anywhere on the page: (my rendition of a four leaf clover)
I'd like to do this using a Java/Ajax script that generates a div, and then places it anywhere on the page. And does not move it once it's been placed, until the page is reloaded.
I've tried so many Google searches, and the closest thing that I've found so far is this (click), from this question. But, removing the .fadein, .delay, and .fadeout stopped the script from working entirely. I'm not by any means a pro with Ajax. Is what I'm trying to do even possible?
Upvotes: 2
Views: 4351
Reputation: 840
This still works. simply use makeDiv() to create new one.
function makeDiv(){
var divsize = ((Math.random()*100) + 50).toFixed();
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
$newdiv = $('<div/>').css({
'width':divsize+'px',
'height':divsize+'px',
'background-color': color
});
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
$newdiv.css({
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
'display':'none'
}).appendTo( 'body' ).fadeIn(100);
};
makeDiv();
Upvotes: 2
Reputation: 129
It the first link suits you, do not remove fadein it shows up the element. Or remove 'display':'none' and then you can remove all you wrote.
Upvotes: 0
Reputation: 1311
In javascript you can generate a a random number between 0 and 1 using var randomNumber = Math.random();
If you give your div absolute positioning, you can then do
div.style.top = (100*Math.random()) + "%";
div.style.left = (100*Math.random()) + "%";
this will set it in a random location. By setting the left and top css properties to a random percentage between 0 and 100.
Upvotes: 6