Display Blog Ads Spots in Random Order

By Sam Deering

To make it fair for everyone who has signed up a jQuery ad on the blog I have wrote a nifty little function to load the ads in a random order. There is also a shuffle button as a demo for creating a random shuffle on the ad spots manually. This function could be made more customisable but does the job.

Try it out for yourself (look at the right sidebar!).


The code

//Function to display ads on the jQuery Blog and shuffle
   var displayAds = {

       ads: {
           1: {
                title: "jQuery UI Widgets for PC, Mobile and Touch devices",
                href: "",
                img: "jqwidgets.png"
           2: {
                title: "jQuery Chop Slider 2.0 - The most eye catching image slider on the internet!",
                href: "",
                img: "idangerous.jpg"
           3: {
                title: "Sauce Labs - Online Cross Browser Testing",
                href: "",
                img: "sauce-labs.jpg"
           4: {
                title: "Diamond Slider - Ken Burns Effect & Unlimited Transitions",
                href: "",
                img: "diamond-slider.jpg"
           5: {
                title: "AJAX Zoom - jQuery Dynamic 2d/360 Degrees Zoom with ipad support.",
                href: "",
                img: "ajax-zoom.jpg"

       signupAd: {
           title: "Advertise here",
           href: ""

       shuffleAds: function(arr)
          for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
          return arr;

       load: function()
           var adContainer = $('#jq4u-sidebar-ads').empty(), adsArray = Array();

           /* construct ads */
           $.each(, function(i,v)
' + v.title + '
'); }); /* shuffle ads in random order */ adsArray = this.shuffleAds(adsArray); /* output ads */ $.each(adsArray, function(i,v) { adContainer.append(v); }); /* add the signup ad */ adContainer.append('
' + this.signupAd.title + '
'); /* show shuffle button */ adContainer.append('Shuffle'); $('#shuffle-ads').live('click', function(e) { e.preventDefault(); displayAds.load(); }); $('#shuffle-ads').show(); } } $(document).ready(function() { displayAds.load(); }); })(jQuery);
  • greg

    this is a useful script, but whats the trick for making it work?
    i set it up (including jquery lib first), made a div with the id listed in the load: and no errors, but not populating div either? o.0

    • jQuery4u

      Hi Greg, did you manage to get it working?



Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.