Rotate Ads in Javascript with Ad-rotator

For many websites, advertisements could mean a substantial source of revenue. Hence, making it appealing, clickable and unobtrusive is an essential base requirement. Lets see how you could easily setup ad rotation on your website with the use of a standalone javascript library Ad-rotator.

Ad Rotation in pure javascript

Ad rotator in javascript

We made a small list of requirements of what we’d expect from an ideal Ad-rotator. These basic requirements were to –

  • display multiple ads in different sizes
  • display ads targeted by device
  • display Ads to Adblock users
  • lazy load Ads
  • have hooks to perform analytics or to log Ad clicks / Ad impressions
  • support sticky advertisements
  • Be free / open source

We can sure write our own ad-rotator, but why reinvent the wheel when we already have a working solution. The library Ad-rotator.js meets all of the requirements listed above! So we decided to go along with it.

Before going any further, here’s a Demo of what the end result looks like. We suggest viewing the page on a desktop as well as a mobile to see how the same advertisements adapt according to the device being used.


Installing and using Ad-rotator.js

The installation instructions are pretty clear in the official docs, but for the sake of completeness, we’re gonna list them here too –

# you can install ad-rotator with npm
$ npm install --save ad-rotator

Then include it in your App/Webpage

import rotator from 'ad-rotator';

// or as a script
<script src="https://cdn.jsdelivr.net/npm/ad-rotator"></script>

Now that adrotator is installed and available, we need only 2 things – the advertisements to be displayed and the location where the advertisements should be displayed.

Adrotator accepts a DOM element (location where ads should be displayed ) as its first parameter.

The second parameter is an array of advertisements. Each advertisement is an object with 2 properties –

  • img – A url to the image/asset
  • url – A url where you want the user to be redirected to on clicking the advertisement

Lets say we wish to display 3 advertisements. Here’s a small code snippet demonstrating how to display them with adrotator:

const instance = rotator(
  document.getElementById('myelement'),   // a DOM element
  [                                       // array of ads
    { url: 'https://site1.com', img: 'https://example/picture1.jpg'},
    { url: 'https://site2.com', img: 'https://example/picture1/picture2.jpg'},
    { url: 'https://site3.com', img: 'https://example/picture1/picture3.jpg'}
  ]
);

// start the rotation
instance.start();

That’s pretty much it! By default, Ads are rotated in a random fashion ensuring no repetition occurs within each rotation cycle. The Ads are rotated after every 5 seconds. Rotation starts only when the Ads are within the view port of the user (i.e. they are visible to the user) and it gets paused when the Ad goes out of the view port ensuring no necessary rotation takes place. All of the default options are completely customizable.

We will check out how to customize configuration options as per our needs.


Custom Configuration options

Ad-rotator accepts an optional 3rd parameter that allows you to configure the various options available.


1. Shape

With Adrotator, you can display Ads in different shapes whose dimensions are set to use the standard Ad unit sizes. The default shape is set to be a square but it is customizable to leaderboard, sidebar, mobile or custom. Using a different shape value updates the size of the Ad unit automatically i.e. its height and width configuration parameters are updated automatically.

Here is a reference of the dimensions used (height x width)

  • Square – 300×250 (px)
  • leaderboard – 90×728 (px)
  • sidebar – 600×300 (px)
  • mobile – 90 x [Width of the mobile device] (px)
  • custom – unset x unset

While using custom, you must set the height and the width parameters yourself. Custom configuration is passed as a 3rd parameter while initializing Adrotator.

const instance = rotator(
  document.getElementById('myelement'),   // a DOM element
  [                                       // array of ads
    { url: 'https://site1.com', img: 'https://example/picture1.jpg'},
    ...
  ],
  { shape: 'sidebar' }                    // configuration options
);

// start the rotation
instance.start();

2. Height, Width of Ad-unit

You can set a custom height and width for your Ad-unit. To do so, you will also have to set the shape of your Ad-unit to be custom.

const instance = rotator(
  document.getElementById('myelement'),   // a DOM element
  [                                       // array of ads
    { url: 'https://site1.com', img: 'https://example/picture1.jpg'},
    ...
  ],
  { shape: 'custom', height: 500, width: 400 }  // configuration options
);

// start the rotation
instance.start();

3. Timer, Target, Random

The timer option controls the time after which an Ad gets rotated. This is fixed to 5 seconds by default.

The target option allows you to specify which device the Ad-unit should be shown. It can be set to desktop, mobile or all. By default, ads are shown on all devices. When target: 'desktop', ads will be shown only on a desktop device whereas when target: 'mobile', ads will be displayed on a mobile device alone.

The random option is a flag that allows controlling the sequence in which the advertisements are shown. The advertisements are rotated in a random fashion by default. Set to false to have them rotated sequentially.

const instance = rotator(
  document.getElementById('myelement'),   // a DOM element
  [                                       // array of ads
    { url: 'https://site1.com', img: 'https://example/picture1.jpg'},
    ...
  ],
  {                                      // configuration options
    timer: 10,                           // Ads will be rotated after every 10 seconds
    target: 'desktop',                   // Ads will be hidden on a desktop
    random: false                        // Ads will be rotated sequentially
  }  
);

// start the rotation
instance.start();

4. Callbacks/Hooks: cb, onHover, onClick

Ad-rotator provides 3 callbacks that can be used for analytics, logging, for controlling Ad-rotator instances or for anything else.

  • cb: This callback is invoked when the rotation starts and each time an Ad-unit is rotated. It receives 3 parameters cb(currentAdUnit, parentElement, configParams)
  • onHover: This callback is invoked each time an Ad-unit gets hovered upon. It works only on a desktop since the hover event is not supported for touch-devices. It receives 2 parameters onHover(currentAdUnit, parentElement)
  • onClick: This callback is invoked when a user clicks on an Ad unit. It receives 2 parameters onClick(event, currentAdUnit)
const instance = rotator(
  document.getElementById('myelement'),   // a DOM element
  [                                       // array of ads
    { url: 'https://site1.com', img: 'https://example/picture1.jpg'},
    ...
  ],
  {                                      // configuration options
    cb: function(adUnit, el, conf) {
      console.log('Displayed Ad =>', adUnit);
      config.timer = 10; // change rotation time to 10 secs
    },
    onHover: function(adUnit, El) {
      console.log("You hovered over this Ad =>", adUnit);
    },
    onClick: function(e, adUnit) {
      alert("You clicked on this Ad. Navigating to " + adUnit.url);
    }
  }  
);

// start the rotation
instance.start();

5. Styling: imgClass, linkClass, objectFit

Here, we list 3 config options that permit setting certain properties/attributes of the DOM elements created by Ad-rotator. These can be useful to control the styling of the elements concerned

  • imgClass: Allows you to add a custom class to the element that will display the Ad.
  • linkClass: Allows you to add a custom class to the link element () that contains the target url of the Ad.
  • objectFit: This option allows you to set the object-fit property of the element. Defaults to 'inherit'

Here’s a small code snippet showing their usage.

const instance = rotator(
  document.getElementById('myelement'),   // a DOM element
  [                                       // array of ads
    { url: 'https://site1.com', img: 'https://example/picture1.jpg'},
    ...
  ],
  {                                      // configuration options
    imgClass: 'responsive-img',          // This class will be added to every <img /> element
    linkClass: 'custom-link',            // This class will be added to every <a /> element
    objectFit: 'cover'                   // Every <img /> will have this object-fit property
  }  
);

// start the rotation
instance.start();

6. Sticky Ads

Ad-rotator permits us to display sticky Ads i.e. Ads that stay visible on the screen. These work for mobiles as well as desktops. By default this setting is disabled, but you can enable it by passing an empty object as per its docs. (sticky: {}). It is recommended that you further configure sticky advertisements as shown below in order to ensure that your Ad is not intrusive and that it does not degrade user experience.

const instance = rotator(
  document.getElementById('myelement'),   // a DOM element
  [                                       // array of ads
    { url: 'https://site1.com', img: 'https://example/picture1.jpg'},
    ...
  ],
  // sticky: {} // this enables stickiness but we recommend the following config
  sticky: {
    beforeEl: document.querySelector('.start'),
    afterEl: document.querySelector('.end'),
    offsetTop: '10',        // or '10px' (defaults to 0px)
    offsetBottom: '150px',  // or '150'  (defaults to 0px)
    noMobile: true          // disable stickiness on mobile (defaults to false)
  }
);

// start the rotation
instance.start();

In the above snippet, the beforeEl refers to the Element after which the Ad becomes sticky whereas the afterEl referes to the Element before which Ad stops being sticky. The offsetTop adds a margin at the top of the Ad whereas the offsetBottom adds a margin at the bottom of the Ad. The noMobile flag can be used when you wish for an Ad to be sticky only on a mobile or not.

Having finished with the config options, lets move ahead to see the API exposed by Ad-rotator.


Ad-rotators API

Ad-rotator exposes 6 handy methods which are very well documented in the official docs. We list them here as well –

  • instance.start() – This one you’re already familiar with. This initaites Ad-rotation.
  • instance.pause() – Pauses the Ad-rotation.
  • instance.resume() – Resumes a paused instance of Ad-rotation.
  • instance.add() – Adds a new Ad-unit on-the-fly to the array of ads.
  • instance.remove() – Removes the last or a particular Ad-unit on-the-fly from the array of ads.
  • instance.destroy() – Destroys Ad-rotation, unsubscribes to events & cleans the DOM.

To use any of the above API methods, simply initalize Ad-rotator and then call the methods as needed. A small JS-fiddle to show ad-rotator in action

Hope that helps 🙂


References

Leave a Reply