4

I have an HTML page with 5 images (48px × 48px each) on it. I want to appear the images at random locations on the webpage everytime the page is loaded.

I don't know how to implement this, I just know I'm going to need CSS and JavaScript (for randomization) for this. Any ideas or suggesions?

Here is sample HTML code:

  <a href="http://twitter.com/"><img alt="Twitter" src="/images/twitter-48.png" /></a>
  <a href="http://facebook.com/><img alt="Facebook" src="/images/facebook-48.png" /></a>
  <a href="https://plus.google.com/"><img alt="Google Plus" src="/images/plus-48.png" /></a>
  <a href="https://github.com/"><img alt="GitHub" src="/images/github-48.png" /></a>
Santosh Kumar
  • 26,475
  • 20
  • 67
  • 118
  • 1
    About PHP: don't forget that it's better to perform work on client always if it's possible and safe to offload your server. About the random positioning - do you already have a containers or image elements and just need assign `src` randomly or you want to set `position:fixed;` and place images randomly within the body? – Eugene Naydenov Sep 16 '12 at 09:44
  • @Santosh, please provide more details. What do you mean by "random location"? Is it supposed to be some container-wrapper inside which images will be absolutely positioned or something else? Provide some markup – d.k Sep 16 '12 at 09:46
  • @caligula, h[is|er] request seemed pretty straight forward to me, he'd like to randomize the location of elements on a page. [S]He is unsure what the proper technology to use is be-it markup/css/javascript. – Korvin Szanto Sep 16 '12 at 09:51
  • @caligula I have updated the question, and I haven't done any CSS stuffs yet. – Santosh Kumar Sep 16 '12 at 10:01
  • @EvgeniyNaydenov See my updated question, I haven't touched the CSS parts. What if I want this to be done in JavaScript. – Santosh Kumar Sep 16 '12 at 10:06

5 Answers5

1

Here's a rather simple implementation: http://jsfiddle.net/Eu8wT/

$('div.randomizeme').css({
    top: Math.random() * 100+'%',
    left: Math.random() * 100+'%'
});​

To apply this over several elements:

$('div.randomizeme').each(function(){
    $(this).css({
        top: Math.random() * 100+'%',
        left: Math.random() * 100+'%'
    });
});​

Here's the same thing without jQuery:

var elements = document.querySelectorAll('.randomizeme');
for (var i in elements) {
    elements[i].style.top = Math.random() * 100 + '%';
    elements[i].style.left = Math.random() * 100 + '%';
}​
Korvin Szanto
  • 4,531
  • 4
  • 19
  • 49
  • Hey it works on [jsFiddle](http://jsfiddle.net/Eu8wT/), but is not working for me. Can you [review it](http://synaptik.co.cc/so/12445851/KorvinSzanto)? – Santosh Kumar Sep 16 '12 at 12:42
  • You're loading the script prior to loading the images, if you do it the other way around it will be fine, or you can wait for the entire page to load using `window.onLoad = function(){ }` – Korvin Szanto Sep 16 '12 at 13:13
  • Moved script to just above the closing body tag (updated that link), but still that problem. – Santosh Kumar Sep 16 '12 at 14:03
  • Its not working outside jsFiddle, can you provide a real world *(on a webpage)* example? – Santosh Kumar Sep 16 '12 at 22:28
  • @Santosh Here is the "no jQuery" version: http://fiddle.jshell.net/dSAzp/show/ it's important to remember that you can only have ONE `window.onload` definition, so if your page has jQuery or another library that uses `window.onload`, try using `document.onload`. I should also let you know that I previously said `window.onLoad` which is incorrect, it's `window.onload` – Korvin Szanto Sep 17 '12 at 04:57
  • Here's an example of never going out of the bounds of the page: http://jsfiddle.net/Jfduu/ – Korvin Szanto Sep 17 '12 at 05:15
1

A solution that uses pure JavaScript (no library)

var imgs = document.querySelectorAll('.rand'), 
    len = imgs.length, 
    /* subtract the width/ height of images */
    w = document.body.clientWidth - 48, 
    h = document.body.clientHeight - 48;

for(var i = 0; i < len; i++) {
  imgs[i].style.top = Math.floor(Math.random() * h) + 'px';
  imgs[i].style.left = Math.floor(Math.random() * w) + 'px';
}

working demo

Ana
  • 35,599
  • 6
  • 80
  • 131
  • @Ana Its working good on [CodePen](http://codepen.io/thebabydino/pen/tyFza), but I don't know why it isn't working for me. Can you [review it](http://synaptik.co.cc/so/12445851/ana)? – Santosh Kumar Sep 16 '12 at 12:21
  • I don't know why, but I've updated the pen and my answer. This is also simpler and I'm thinking it should work :-? – Ana Sep 16 '12 at 12:41
  • the new version works for me when I try it on your site using developer tools. – Ana Sep 16 '12 at 12:49
  • @Ana Really? I have updated the JavaScript, but it is as it was. The images appears to be overlapping each other, thus showing only one image. Did you tried it in your browser (locally)? – Santosh Kumar Sep 16 '12 at 12:59
  • I ran it in the console on your site. And I think I have now figured out why it wasn't working. It said `document.body` was `null` and that's logical, since you put it in the `head`, *before* the `body`. You should put the script right before you close the `body` tag. – Ana Sep 16 '12 at 14:04
  • @Ana What was the reason you fixed the length and width of image to `48px`, it seems to work without it. – Santosh Kumar Sep 17 '12 at 01:44
  • Because you said your images are `48px` x `48px` each. The ones I used are not, they are actually bigger, so that's how I scaled them down. – Ana Sep 17 '12 at 09:12
-1

Lets assume that you already have the images hardcoded on to your html document. What you would need to do (if you want to accomplish this with PHP) is add a style attribute to each element. In your case, your images are held within <a> tags, so you'll want to position the <a> tag randomly and not the images...

function generateRandomPositions(){

  // define maximum and minimum 'top' values
  $maxTop = 1000;
  $minTop = 0;

  // define maximum and minimum 'left' values    
  $maxLeft = 1000;
  $minLeft = 0; 


  $styleProperties = array(
    'position:absolute',
    'top:'.rand($minTop,$maxTop) . 'px',
    'left:'.rand($minLeft,$maxLeft) . 'px'
  );

  return ' style="'.implode(';',$styleProperties).'" ';
}

The function will return a string similar to this -

style="position:absolute;top:10px; left:45px;"

Now all you have to do is call this function for each image on your page -

<a <?php echo generateRandomPositions();?> ><img src="...
<a <?php echo generateRandomPositions();?> ><img src="...
<a <?php echo generateRandomPositions();?> ><img src="...
<a <?php echo generateRandomPositions();?> ><img src="...

Your <a> tags will now contain random CSS positioning parameters and their images will move with them.

As I'm sure you can see, this method of using PHP to generate inline CSS properties is kind of a backwards way to do this. JavaScript would probably be the best way to get what you are looking for and there are other answers that cover it. You could initially hide your elements with CSS and then display them with the JavaScript after you have set the random positioning.


References -

Lix
  • 47,311
  • 12
  • 103
  • 131
  • 1000x1000 screen? It would make 1000x more sense to use %, also, this sort of operation should not be done with PHP. – Korvin Szanto Sep 16 '12 at 10:24
  • @kor - the 100opx limit was just an example I gave for the limits. I am clearly aware that PHP is not the way to do this however the original post *was* asking about PHP - it's an alternative. – Lix Sep 16 '12 at 10:31
  • 1
    not trying to be abrasive, but his question was which technology would be best to use, he then stated that he thinks php to be the best. I'm glad that you understand this, but you should state that there are better ways. – Korvin Szanto Sep 16 '12 at 10:34
  • @Lix Works as I expected, any way to prevent overlapping? – Santosh Kumar Sep 16 '12 at 10:51
  • @san - That's kind of the problem with the randomization. You would have to re-generate a random location and each time check it against existing values that you have already generated. Remember to add the width and height of the element to the values to make sure there are no overlapping. – Lix Sep 16 '12 at 10:53
  • @Lix I have changed `$maxTop` and `$maxLeft` to `100` and replaced `px` to `%`. But I don't want images to appear beyond the fold. I tried changing maxTop and maxLeft to even 95%, but it didn't worked. – Santosh Kumar Sep 17 '12 at 03:14
-1
<?php
$images= array(
    'twitter-48.png',
    'facebook-48.png',
    'plus-48.png',
    'github-48.png'
);
$keys= range(0, count($images)- 1);
shuffle($keys);
foreach($keys as $key) {
    print "<div>{$images[$key]}</div>";
}

EDIT:

<?php
$images= array(
    array('href'=> 'http://twitter.com/', 'alt'=> 'Twitter', 'src'=> '/images/twitter-48.png'),
    array('href'=> 'http://facebook.com/', 'alt'=> 'Facebook', 'src'=> '/images/facebook-48.png'),
    array('href'=> 'https://plus.google.com/', 'alt'=> 'Google Plus', 'src'=> '/images/plus-48.png'),
    array('href'=> 'https://github.com/', 'alt'=> 'GitHub', 'src'=> '/images/github-48.png')
);
$keys= range(0, count($images)- 1);
shuffle($keys);
?>
<div class='location1'>
    <a href='<?php print $images[$keys[0]]['href']; ?>'><img alt='<?php print $images[$keys[0]]['alt']; ?>' src='<?php print $images[$keys[0]]['src']; ?>'></img></a>
</div>
<div class='location2'>
    <a href='<?php print $images[$keys[1]]['href']; ?>'><img alt='<?php print $images[$keys[1]]['alt']; ?>' src='<?php print $images[$keys[1]]['src']; ?>'></img></a>
</div>
<div class='location3'>
    <a href='<?php print $images[$keys[2]]['href']; ?>'><img alt='<?php print $images[$keys[2]]['alt']; ?>' src='<?php print $images[$keys[2]]['src']; ?>'></img></a>
</div>
<div class='location4'>
    <a href='<?php print $images[$keys[3]]['href']; ?>'><img alt='<?php print $images[$keys[3]]['alt']; ?>' src='<?php print $images[$keys[3]]['src']; ?>'></img></a>
</div>
HanhNghien
  • 225
  • 1
  • 6
-2

Try this:

$images = array('1.gif', '2.gif', '3.gif');
$images = array_shaffle($images);
foreach ($images as $image) {
  echo "<img src='{$image}' />;
}
MrSil
  • 608
  • 6
  • 12
  • 1
    array_shaffle? Also, you didn't close your `"`. Finally, this doesn't quite answer the question posed. – Korvin Szanto Sep 16 '12 at 09:47
  • 1
    Rather `bool shuffle(array &$array)`; I've just edited this answer, awaiting of accept. – Eugene Naydenov Sep 16 '12 at 09:51
  • @evg - Please do not edit code blocks from other peoples posts. They can (and probably will) drastically change the outcome of the provided solution. In these cases it is better to leave a comment for the OP and let them take care of it. – Lix Sep 16 '12 at 10:04