How To Build a Custom Ad Banner Rotator Script with jQuery




There are so many reasons why you may consider using JavaScript as a random banner generator instead of a backend server language. But the primary reason is when using a caching system, as the banner advertisement itself will only randomize once for the cache. Then it stays the same on every pageview. However with JavaScript we can generate a new random number every page refresh and display one of a set of banners on the page – while keeping with the same theme as caching.

In this tutorial I want to demonstrate how we can build a JavaScript banner rotator which works even over PHP/Rails caching. You only need to implement the codes on your frontend, which means the settings on your web server do not matter as much. The script will hold an array of content data which matches up based on the image and outbound links. Take a peek at my live sample demo to catch a glimpse into what we will be creating.

jquery javascript advertising rotator banner tutorial preview

Live DemoDownload Source Code

Getting Started

Looking at the HTML we really do not need a whole lot of stuff on the page. I will be using a wrapper with an internal banner container. This container will hold the ID which we target for manipulating the internal img tag. As far as related libraries, we only need a copy of jQuery and some external CSS styles.

<!doctype html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>JavaScript Ad Rotator Demo - SpyreStudios</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="shortcut icon" href="http://spyrestudios.com/favicon.ico">
  <link rel="icon" href="http://spyrestudios.com/favicon.ico">
  <link rel="stylesheet" type="text/css" media="all" href="css/styles.css">
  <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
  <script type="text/javascript" charset="utf-8" src="js/ads-rotator.js"></script>
</head>

It is important to recognize that we need to leave some of the page elements blank. The HTML image banners will generally appear blank once the DOM loads, or we can use a spacer .gif image. Or even another placeholder advertising banner which gets replaced via JavaScript. But ideally we can use the lone ID on any banner ad container for targeting internal elements.

  <div id="w">
    <h1>JavaScript Ad Banner Rotator</h1>
    <p>Refresh the page and you can see the banner image change each time. The purpose of using JS over PHP/HTML is when used alongside caching. Banner ads will cache and the easiest way to avoid this would be to rotate using JavaScript.</p>
    
    <div id="topad">
      <a href=""><img src="" alt="advertisement" width="728" height="90"></a>
    </div><!-- @end #topad -->
  </div><!-- @end #w -->

The two key objects we need to manipulate would be the image’s src attribute, along with the containing anchor link’s href attribute. Both of these values are stored as variables inside a JavaScript array. All of the banner designs for this demo are sized as leaderboards with 728×90 being the standard dimensions.

Basic Page Styles

There is not a whole lot of interesting CSS styles worth explaining. I am using a typical block of CSS resets which helps to get the page into a baseline for all browsers. Many developers are adamantly against this technique, yet I still feel it works perfectly in consideration with sample demo pages.

h1 { 
  font-size: 3.2em;
  line-height: 1.6em;
  margin-bottom: 10px;
  font-weight: bold;
  text-align: center;
  padding: 5px 9px;
}
p { 
  font-size: 1.4em;
  line-height: 1.3em;
  color: #545454;
  margin-bottom: 20px;
}
a { color: #8ca6d2; }
a:hover { color: #9cb4dd; }

#w { 
  display: block; 
  width: 750px; 
  margin: 0 auto; 
  background: #fff; 
  padding: 4px 15px; 
  padding-bottom: 22px; 
  -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.4);
  -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.4);
  box-shadow: 1px 2px 2px rgba(0,0,0,0.4);
}

The outer wrapper div is centered on the page using a width of 750px. Also a small bit of CSS3 box shadow which adds flair into the design. But notice how I have not included any other additional CSS properties targeting the advertising div. It goes to show that we can manipulate images on the page without styling them at all. Of course, in your own layouts it does make sense to organize the positioning, margins, padding, and other aspects of the page.

Randomizing Adverts

I’ll now be looking inside my own custom file ads-rotator.js. The code does require storing a bit of data into large variables, so we can tackle those first. I have two major arrays containing 9 indices each. The first variable adBanners will contain the image source URLs, while the second variable bannerLinks holds the outbound URLs.

$(function(){
  var adBanners = [
    "txp-leaderboard-728x90.jpg",
    "basic-textpattern-728x90.jpg",
    "wordpress-mythemesshop-728x90.jpg",
    "mwp_banner_18_728x90.jpg",
    "grooveshark-ad-728x90.jpg",
    "treehouse-learning-ad-728x90.jpg",
    "ddg-duck-duck-go-ad-728x90.jpg",
    "photoshop-to-html-ad-728x90.jpg",
    "getting-good-javascript-ad-728x90.jpg"
  ];
  var bannerLinks = [
    "http://textpattern.com/",
    "http://textpattern.com/",
    "http://mythemeshop.com/",
    "https://managewp.com/",
    "http://grooveshark.com/",
    "http://teamtreehouse.com/",
    "https://duckduckgo.com/",
    "http://rockablepress.com/books/photoshop-to-html",
    "http://rockablepress.com/books/getting-good-with-javascript"
  ];

If you are clever with .htaccess it is easily possible to update these outbound URLs to be relative from your domain. This may appear less like an advertisement, and so visitors are more willing to click through onto another page. The rest of the script creates a new barrage of variables for handling relative URLs, along with dynamically replacing these attributes.

  var imgPrefix   = "images/";
  var randNum     = Math.floor(Math.random() * (8 - 0 + 1)) + 0; /* http://stackoverflow.com/a/1527834/477958 */
  var topAdBanner = $('#topad > a > img');
  
  var newBannerImg  = imgPrefix + adBanners[randNum];
  var newBannerLink = bannerLinks[randNum];
  
  // update new img src and link HREF value
  $(topAdBanner).attr('src',newBannerImg);
  $('#topad > a').attr('href',newBannerLink);

Obviously the imgprefix should be a URl pointing to your website’s banner images folder. It should be relative from the HTML file and not from the JS file. You can avoid this by making the prefix an absolute URL(ex: http://spyrestudios.com/images/ads/). randNum is a variable consisting of values 0-8 which correspond to individual array elements.

I found this excellent line of code in a Stack Overflow response which was perfect for this script. You can obviously edit the values to fit your own needs if the number of banners exceeds nine choices. The variables newBannerImg and newBannerLink use this random number in combination with the array variables created earlier. So if we get a random number of 4, we can pass that index into both arrays and get the 4th banner image/source URL.

By applying the jQuery .attr() method it is easy to manipulate the anchor HREF and the image SRC values. After the DOM has finished resolving, it will become apparent almost immediately once the advertising banner finishes loading as well. This script is an excellent workaround when you need caching on the backend, yet still need to rotate between advertisers on each webpage.

jquery javascript advertising rotator banner tutorial preview

Live DemoDownload Source Code

Final Thoughts

Plenty of online websites including blogs will be in favor of dynamically generated banners. The HTML code itself may not conform to exact standards, but the purpose of a banner rotator is for displaying partially dynamic content. So Google crawlers shouldn’t be concerned with indexing the images anyways. I do hope this tutorial may help some web developers who have been interested in this idea. Feel free to download a copy of my source code and share any questions or comments with us in the discussion area below.


Jake Rocheleau

About the author:

Jake is a creative designer, illustrator, and web developer. He frequently writes articles involving new-age design concepts and freelance management skills. You can find him in Google or follow his tweets @jakerocheleau

Comments:

Scroll back to the top
Content


Receive the top stories from SpyreStudios and the Splashpress Media network every week, right in your Inbox. Relevant and timely content is yours for FREE!