Grow your CSS skills. Land your dream job.

Random Ad Positions

Published by Chris Coyier

If you have multiple display ads of the same size in a block on your site, a good thing to do is randomize their position in the block. It's more fair to the advertisers and the different layouts reduce ad blindness. The ads currently on this site from BuySellAds do this automatically, but if you have your own manual system, here are three different ways to randomize.

View Demo   Download Files

Technique #1) Randomize with PHP, random starting image

I think doing the randomization server side is ideal so that the ads are already randomized when the page loads. My first idea was to generate a random number between one and the total number of ads. Then run 2 for loops, one from 1 to that random number and one from that random number to the total.

<?php
      $totalImages = 6;
      
      $randomFirst = rand(1,$totalImages);
      
      for ( $i=$randomFirst; $i <= $totalImages; $i++ ) {
          echo "<img src='images/ad-$i.png' alt='ad' /> ";
      }
      
      for ( $i=1; $i < $randomFirst; $i++ ) {
          echo "<img src='images/ad-$i.png' alt='ad' /> ";
      }
?>

Works fine, but it's not as random as it could be. Only the starting ad is random but the order is always the same.

Technique #2) Randomize with PHP, random order

To get more random, PHP has a built in function for randomizing an array. So just set up the array using the range function from 1 to the total number of ads, randomize it, then spit it out with a foreach loop:

<?php
      $totalImages = 6;
      
      $all = range(1,$totalImages);
      shuffle($all);
      
      foreach ($all as $single) {
          echo "<img src='images/ad-$single.png' alt='ad' /> ";
      }
?>

Technique #3) Randomize with jQuery

This is less ideal because of the possibility of the images loading and then the JavaScript kicking in and shuffling them (awkward). Although, the randomization does happen on DOM ready, so theoretically it should happen before the images load. This would be most useful when you CAN control JavaScript on the page but NOT control the HTML.

The technique here is to load up jQuery and load the shuffle plugin by James Padolsey, then just target the images and call the function:

(function($){
 
    $.fn.shuffle = function() {
 
        var allElems = this.get(),
            getRandom = function(max) {
                return Math.floor(Math.random() * max);
            },
            shuffled = $.map(allElems, function(){
                var random = getRandom(allElems.length),
                    randEl = $(allElems[random]).clone(true)[0];
                allElems.splice(random, 1);
                return randEl;
           });
 
        this.each(function(i){
            $(this).replaceWith($(shuffled[i]));
        });
 
        return $(shuffled);
 
    };
 
})(jQuery);

$(function() {

    $("#ad-group-one img").shuffle();

});

 

Any other randomization techniques out there?

Comments

  1. wow, that will be very useful for me. searching for hours now for a solution about banners/ads.

    thank you very much :)

  2. I wish the php method was explained a little bit more thoroughly. Like, line by line. :)

    Thanks for this Chris.

  3. Certainly this post is great to help folks understand how things work, but I just wanted to mention that there’s a great plugin for WordPress by Nico that can handle the 125px X 125px advertising blocks. You can set them to be static or rotate:

    http://blogio.net/blog/wp-ad-plugin/

  4. If you store all the adds in an array, you can simply shuffle(); the array with a built in php function:

    http://ca3.php.net/manual/en/function.shuffle.php

  5. Permalink to comment#

    If the ads are stored in a mysql database you can have the database do the work for you –

    select ad_src from ads order by rand()

    • Ptitoine
      Permalink to comment#

      if you use the mysql rand function in your query, mysql will never cache the query …

      you are better to fetch all the ads from mysql and randomize them with php

    • Permalink to comment#

      this is the one i always prefer! :-)

  6. The 2nd technique displayed is the way i like to do it, Ive tried using jQuery and it can have undesired effects on the occasion.

    Also Angelo, doesn’t that code simply randomise a single image rather than displaying them all but in random positions?

    I think using a mySQL database is a bit too overkill for something that is fairly simple to do.

    Just my thoughts anyway!

    • For some reason it took out the echo statement, but essentially you’ll be echoing the image out.

    • Permalink to comment#

      I’m trying to add images to a website that im building. I could use your help. Thanks

  7. Per
    Permalink to comment#

    As many have probably said already, a database solution would be optimal for this sort of thing. You could make a little admin panel for it for easy management and so forth. This comment doesn’t have anything to do with the random placement of the ads themselves but I’d say it builds upon this idea.

  8. Permalink to comment#

    Chris,

    in 1st technique use “mt_rand” instead of “rand”.

    • Matt
      Permalink to comment#

      Agreed. If you get thousands of hits per day, or per hour for that instance, save yourself some clocks and use mt_rand.

  9. Ben
    Permalink to comment#

    You would still ignore those ads though. You would need them spread randomly across the page. In a subtle way though.

  10. My personal approach is to move away from a block of ads and instead position of ads throughout the text, with PHP randomly floating the ad against one of the paragraphs.

    I would like to add to the shuffle() method though. Rather than using an array of numbers, create an array of filenames/image URLs and shuffle that instead. That means you can show ads from external locations or that don’t all originate from the same domain.

  11. Nyte
    Permalink to comment#

    Offtopic:
    Whats with the very very ugly and unfriendly redesign?

    Main post with an “in your face-ad” and then 4 ugly hard to read older articles?

    It was way better when it was still a blog so you could read more articles then just the latest.

    • I agree Nyte, much better before, trying a bit too hard to be like http://www.smashingmagazine.com which suffers from the issue.

    • V1
      Permalink to comment#

      That’s what happens when design is king, instead of content.

      Big blubbery pile of mess

    • I’m all for criticism but this is all totally useless.

      “very very ugly”

      “unfriendly”

      “big blubbery mess”

      What does any of that mean? That’s not useful criticism it’s just negative words. Why don’t you pull a real critique together and publish it, I’d love to see it.

    • Maybe they are just mad that nobody wants to pay to advertise on their sites….eh…
      Anyways, great post. And I happen to like the redesign.

    • Permalink to comment#

      I’m just bummed that the little creature disappeared from the footer. What was his name? I kind of liked the old design, too, but maybe the new one just has to grow on me. Cheers.

    • I agree with Chris, if you’re gonna criticise a good designer, you need to have a point to it, all you have done here is prove that you are unable to give reason to your argument.

      As for the criticism of the redesign, personally I like it, and in my opinion design needs to be changed all the time to keep us thinking, so now instead of stringing together useless hate, why not decide why you don’t like it, and post a reply with your reasons in good English.

  12. Permalink to comment#

    Is this applicable if I use ad networks like adsense or adbrite?

  13. Permalink to comment#

    Good advices, makes sense

  14. I agree, Im not such a fan of ads in blocks. Spread them out thoughout the page, just looks alot better.

  15. Permalink to comment#

    hi there, I’m using the jQuery method and want to know how to show random six pictures pertime while having 20 pictures

  16. Nice php trick for randomized ad position. It can be used for other random content placement as well. Thanks for this cool tip.

  17. Ant
    Permalink to comment#

    I never clicked them anyway.

  18. Brent
    Permalink to comment#

    You could consider me, relatively…ignorant when it comes to php. So, that said, with Technique #2, how would you get the links on there and make sure that they match the random images that you’re puling?

  19. Can i use it with wordpress?

  20. Unfortunately, none of these options work in the instance where you have adverts with multiple weightings.

    It would be good to see a solution for that.

This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".