Skip to content

Instantly share code, notes, and snippets.

@benwong
Created July 19, 2012 01:36
Show Gist options
  • Save benwong/3140195 to your computer and use it in GitHub Desktop.
Save benwong/3140195 to your computer and use it in GitHub Desktop.
Javascript Rotating Ad Banner
var currentBannerIndex = 0;
var banners = [
{ image: 'banner-1.jpg', url: 'http://test.com/1' },
{ image: 'banner-2.jpg', url: 'http://test.com/2' },
{ image: 'banner-3.jpg', url: 'http://test.com/3' },
];
function getRandom(max) {
var rand = Math.random();
rand = Math.floor(rand * 1000000);
rand = (rand % max);
return rand;
}
function appendBanner() {
var index = getRandom(3);
currentBannerIndex = index;
$('div.page').append('<div class="banner-ad"><a href="' + banners[index]['url'] + '" target="_blank"><img src="banner-images/' + banners[index]['image'] + '" alt="banner" /></a></div>');
setTimeout(changeBanner, 5000);
}
function changeBanner() {
currentBannerIndex++;
if (currentBannerIndex >= banners.length) {
currentBannerIndex = 0;
}
$('.banner-ad').fadeOut(function () {
$('.banner-ad a').attr('href', banners[currentBannerIndex]['url']);
$('.banner-ad img').attr('src', 'banner-images/' + banners[currentBannerIndex]['image']);
$(this).fadeIn();
});
setTimeout(changeBanner, 5000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment