The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Making random not so random Reply To: Making random not so random


I really only replaced two lines that define the x and y position the elements will be placed (what I called the randomisers) :

fixLeft = Math.round(Math.random()*($(window).width()-400))+40;
fixTop = Math.round(Math.random()*($(window).height()-50))+40;

Just to be clear, I’ll describe the whole thing…

In this, fixLeft and fixTop are the x and y positions that will be assigned to each of the objects (the divs with text in your case).

The bits $(window).width() and $(window).height() are jQuery (JavaScript library) – the width and height of the screen size are measured with this. Plain JavaScript would need a bit of different code here but I automatically used these because they are very reliable (besides the quick copy and paste I did).

A random rounded number is then taken from these values (Math.round(Math.random()) to determine the positioning. But the dimensions of the items themselves have to be accounted for so they don’t overflow / stick out of the window. That’s the number that will have to be distracted from the screen width and height.
In the fiddle, I just guessed a bit…

Value at the end you could see as the margin, the minimum x and y position an element will be placed. Needless to say they will have to be tweaked for it to work flawlessly, like if you want the same bottom and right margins. Simple if you give the elements a fixed width as seen on the example page. Differently sized container would need additional calculation. And at small screen sizes things might get crowded.

That site has a neat / smart thing going on by the way. If you resize the browser window, the objects will only start to switch position when the mouse button is released. Gotta remember that.
Edit there – I think it’s a timeout, not a mouseup.

As to filling up the screen – that would take quite a different approach. I’d have to come back on that (or other members that know of a good idea of course). Don’t have an answer ready there.