[Solved] Javascript Ad Banner Rotator for my website? [closed]


In the future, try to give this a shot for yourself and ask more specific questions. I don’t see why you don’t want to use a service if you’re not writing it anyway.

However, since you are, here’s my suggestion.

Javascript:

var banners = [
  {
    "img": "tnl-banner-steve-jobs-01.png",
    "url": "http://news.stanford.edu/news/2005/june15/jobs-061505.html",
    "weight": 1
  },
  {
    "img": "tnl-banner-steve-jobs-02.png",
    "url": "http://news.stanford.edu/news/2005/june15/jobs-061505.html",
    "weight": 1
  },
  {
    "img": "tnl-banner-steve-jobs-03.png",
    "url": "http://news.stanford.edu/news/2005/june15/jobs-061505.html",
    "weight": 1
  },
  {
    "img": "tnl-banner-steve-jobs-04.png",
    "url": "http://news.stanford.edu/news/2005/june15/jobs-061505.html",
    "weight": 1
  },
  {
    "img": "tnl-banner-steve-jobs-05.png",
    "url": "http://news.stanford.edu/news/2005/june15/jobs-061505.html",
    "weight": 4
  }
];

And here’s the script to add into your HTML:

<script>

// Fetch the banner setup file.
var filename = getURLParameter("type")+".js";
jQuery.getScript(filename, function(){
  var banner = randomBanner();
  // Add the banner to the page body.
  $('body').append("<a target=\"tnl_ad\" href=\""+banner["url"]+"\">" +
    "<img src=\"banners/"+banner["img"]+"\"></a>");
})
  .fail(function(jqxhr, settings, exception) {
    console.log("Error parsing " + filename + ": " + exception.message);
  }
)

function randomBanner() {
    var totalWeight = 0, cummulativeWeight = 0, i;
    // Add up the weights.
    for (i = 0; i < banners.length; i++) {
        totalWeight += banners[i]["weight"];
    }
    console.log("Total weight: " + totalWeight);
    var random = Math.floor(Math.random() * totalWeight);
    // Find which bucket the random value is in.
    for (i = 0; i < banners.length; i++) {
        cummulativeWeight += banners[i]["weight"];
        if (random < cummulativeWeight) {
            return(banners[i]);
        }
    }
}

function getURLParameter(name){
  return decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]);
}
</script>

Source

4

solved Javascript Ad Banner Rotator for my website? [closed]