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
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
- Set a priority on the Ads being displayed
- display ads specific to devices (desktop/mobile)
- 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'; // include library import 'ad-rotator/dist/style.css'; // include basic style (optional) // or via CDN <script src="https://cdn.jsdelivr.net/npm/ad-rotator"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ad-rotator/dist/style.css" />
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.
<div id="myelement"></div> <!-- create DOM element --> <style> #myelement { /* sets Ad size */ height: 600px; width: 300px; } #myelement img { /* set img elements to be responsive */ height: 100%; width: 100%; } </style>
The second parameter is an array of advertisements. Each advertisement is an object that requires 2 properties to function –
- Required:
img
– A url to the image/asset - Required:
url
– A url where you want the user to be redirected to on clicking the advertisement - Optional:
weight
– A weight or a priority applied to the current Ad unit - Optional:
title
– A small text describing the Ad which is used for improving accessibility/SEO.
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.com/picture1.png', title: 'Lorem Ipsum'}, { url: 'https://site2.com', img: './picture2.jpg', weight: 4}, { url: 'https://site3.com', img: 'example.com/picture3.webp'} ] ); // 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 viewport of the user (i.e. they are visible to the user) and it gets paused when the Ad goes out of the viewport ensuring no necessary rotation takes place. All of the default config options are completely customizable.
Note that we set weight: 4
for the 2nd Ad used above ({ url: ‘https://site2.com’, …). By assigning a weight to an Ad unit, we increase its priority and thereby its chances of being shown first. When the rotation is randomized, only its chances are increased but there is no guarantee of it being shown first (as expected with truly random rotation). To sort Ads by their weight (highest to lowest), turn off random rotation by setting the config option – random: false
. Ads with missing weights are automatically assigned a weight of 1.
Lets see 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.
const instance = rotator( document.querySelector('#myelement'), // DOM element [ ... ], // Array of Ads { ... } // custom configuration );
1. Timer, Target, Random, newTab
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 (i.e. in the order they appear in the Array or if the weight option is used, then Ads will be sorted by their weights)
The newTab
option is a flag to control the destination of the target Url (i.e. if it should be opened in a new tab or in the current window). Set to true
if you wish to be navigated to a new Tab. By default, it is set to false
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, // Rotate Ads after every 10 sec target: 'desktop', // Show Ads on desktop alone random: false, // Show Ads sequentially newTab: true // Open target Url in new Tab } ); // start the rotation instance.start();
2. 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 parameterscb(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 parametersonHover(currentAdUnit, parentElement)
onClick
: This callback is invoked when a user clicks on an Ad unit. It receives 2 parametersonClick(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();
3. Fallback Mode
In fallback mode, Ads are shown only if the library detects an Adblocker. This is specially useful if you wish to display Ads from another provider like Google, Amazon, Carbon, etc. and want to use Ad-rotator.js only as a fallback solution.
To activate this mode, set the fallbackMode: true
in the config options.
const instance = rotator( document.getElementById('myelement'), // a DOM element [ // array of ads { url: 'https://site1.com', img: 'https://example/picture1.jpg'}, ... ], { // configuration options fallbackMode: true } ); // start the rotation instance.start();
Tested for most Ad blockers (Adblock, Adblock Plus, Adblock ultimate, ublock origin, etc) as well as Brave’s shields. Kindly open an issue in case fallback mode fails for a certain browser/extension. Meanwhile feel free to test this mode on JS fiddle.
4. Styling: imgClass, linkClass
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 theimg
element that will display the Ad.linkClass
: Allows you to add a custom class to the link element (a
) that contains the target url of the Ad.
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 } ); // start the rotation instance.start();
5. 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 the official 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 config below: 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
- https://www.kunal-chowdhury.com/2012/07/how-to-create-adrotator-using-javascript.html
- https://www.searchenginegenie.com/Javascript-Ad-Rotator.php
- https://webgilde.com/en/ad-rotation-javascript/
- https://www.w3schools.com/asp/asp_adrotator.asp
- https://rotator.digitalfortress.tech/
- https://javascriptsource.com/banner-ad-rotator/
- https://www.tutorialspoint.com/asp.net/asp.net_ad_rotator.htm