Random Ad Positions

Avatar of Chris Coyier
Chris Coyier on

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?