Configuration

Ad-rotator.js provides several configuration options to fine-tune and customize rotation. Only the first two are required whereas the rest are optional that use sensible default values. All available config options are listed below.


1. DOM Element (Required)

This is the DOM input element that ad-rotator will use as a container element to inject Ad-units into. It is a required property and an error is thrown if it is missing.


2. Ads (Required)

This is the source of Ads which will be displayed. It accepts an array of Ads/objects where each object can have 4 properties.

  1. img: string (required) - A url to the image/asset. You are free to use base64 encoded images too.
  2. url: string (required) - The target url where the user will be redirected on clicking the Ad.
  3. weight: number (optional) - A weight or a priority applied to the Ad. The higher the weight, the greater the chances of the Ad being shown. Ads with missing weights are automatically assigned a weight of 1.
  4. title: string (optional) - A small text describing the Ad which is used for improving accessibility/SEO.

JS
const instance = rotator(
  document.querySelector('.publicity_container'),  // DOM element (required)
  [                                                // array of Ads  (required)
    { url: 'https://site1.com', img: './picture1.jpg', title: 'Lorem Ipsum', weight: 4 },
    { url: 'https://site2.com', img: 'https://example.com/image2.png', title: 'On Sale!' },
    { url: 'https://site3.com', img: 'example.com/picture3.webp', weight: 2 }
  ]
);

In the example above, we set weight: 4 for the 1st Ad used. 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 display Ads by their weight (highest to lowest), turn off random rotation by setting the config option – random: false.


3. ⚙️ Custom Config

Ad-rotator accepts an optional 3rd parameter that allows you to fine-tune configuration.

JS
const instance = rotator(
  document.querySelector('.container'),  // DOM element (required)
  [
    // array of Ads  (required)
  ],
  {
    // custom config options [optional]
  }
);

There are several custom config options available as listed below...


A. ⏰ timer

The timer (Type: integer) config option specifies the time after which an advertisement will be rotated in seconds. Lowest accepted value is 2 seconds.

JS
const instance = rotator(
  document.querySelector('.container'),
  [ ... ],     // array of Ads
  {
    timer: 3,  // default - 5
  }
);

Going by the above snippet, Ads will be rotated after every 3 seconds. By default, Ads are rotated after every 5 seconds.


B. random

The random (Type: Boolean) config option controls the fashion of Ad-rotation. When set to false, ads are rotated sequentially i.e. in the order they are provided in the Array. By default, this option is set to true, i.e. ads are rotated randomly.

JS
const instance = rotator(
  document.querySelector('.container'),
  [ ... ],     // array of Ads
  {
    random: false, // default - true
  }
);

Note: The weight property of the Ads array overrides the default behaviour of this option.


C. newTab

The newTab (Type: Boolean) config option is used to control the destination of the target URL (i.e. if it should be opened in a new tab or in the current tab/window).. Set to true if you wish to be navigated to a new Tab.

JS
const instance = rotator(
  document.querySelector('.container'),
  [ ... ],     // array of Ads
  {
    newTab: true, // opens target URL in a new Tab
  }
);

By default, it is set to false, i.e. the target URL is opened within the same tab/window.


D. 🎯 target

The target (Type: Enum) config option allows you to specify the device on which Ads should be shown. It can be set to desktop, mobile or all. If we set target: 'desktop', ads will be shown only on a desktop device whereas if we set target: 'mobile', ads will be displayed on a mobile device alone.

JS
const instance = rotator(
  document.querySelector('.container'),
  [ ... ],     // array of Ads
  {
    target: 'desktop', // default - all
  }
);

By default, the target config option is set to all meaning Ads are shown on all devices.


E. 🪝 cb (callback hook)

The cb() config option is a callback that is invoked when the rotation starts and each time an Ad-unit is rotated.

It receives 3 parameters - unit (the current Ad unit), El (the container html element) and conf (the current config parameters).

JS
const instance = rotator(
  document.querySelector('.container'),   // a DOM element
  [                                       // array of ads
    { url: 'https://site.com', img: 'https://example/picture.jpg'},
    // ...
  ],
  {                                      // configuration options
    cb: (adUnit, el, conf) => {
      console.log('Displayed Ad =>', adUnit);
      config.timer = 10; // change rotation time to 10 secs
    },
  }
);

The cb hook is optional. It can be used for analytics or to change configuration on the fly.


F. onHover hook

The onHover() config option is a callback that 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 - item (the current Ad unit) and El (the html Ad container)

JS
const instance = rotator(
  document.querySelector('.container'),   // a DOM element
  [                                       // array of ads
    { url: 'https://site.com', img: 'https://example/picture.jpg'},
    // ...
  ],
  {                                      // configuration options
    onHover: (adUnit, El) => {
      console.log("You hovered over this Ad =>", adUnit);
    },
  }
);

The onHover() callback is optional and can be used for analytics or to execute some action.


G. 🖱️ onClick hook

The onClick() config option is a callback that is invoked when a user clicks on an Ad unit.

It receives 2 parameters - event (the click event) and unit(the current Ad unit)

JS
const instance = rotator(
  document.querySelector('.container'),   // a DOM element
  [                                       // array of ads
    { url: 'https://site.com', img: 'https://example/picture.jpg'},
    // ...
  ],
  {                                      // configuration options
    onClick: (e, adUnit) => {
      // e.preventDefault();
      alert("You clicked on this Ad. Navigating to " + adUnit.url);
    }
  }
);

The onClick() callback is optional and can be used for analytics, to execute some action or to modify the default navigation action.


H. ⚜️ fallbackMode

The fallbackMode (Type: Boolean) config option is used when you wish to use Ad-rotator.js only as a fallback. 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.

JS
const instance = rotator(
  document.querySelector('.container'),   // a DOM element
  [                                       // array of ads
    { url: 'https://site.com', img: 'https://example/picture.jpg'},
    // ...
  ],
  {                                      // configuration options
    fallbackMode: true, // default - false
  }
);

By default, it is set to false, i.e. the fallback mode is disabled and Ads will be injected irrespective of whether an Adblocker is active or not.

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.


I. imgClass

The imgClass (Type: String) config option is used to add a custom class to the <img /> element.

JS
const instance = rotator(
  document.querySelector('.container'),   // a DOM element
  [                                       // array of ads
    { url: 'https://site.com', img: 'https://example/picture.jpg'},
    // ...
  ],
  {                                      // configuration options
    imgClass: 'rounded',                 // default - ''
  }
);

The default value of imgClass is set to an empty string (''). It can be used for styling image elements.


J. linkClass

The linkClass (Type: String) config option is used to add a custom class to the <a /> element.

JS
const instance = rotator(
  document.querySelector('.container'),   // a DOM element
  [                                       // array of ads
    { url: 'https://site.com', img: 'https://example/picture.jpg'},
    // ...
  ],
  {                                      // configuration options
    linkClass: 'fancy-link',             // default - ''
  }
);

The default value of linkClass is set to an empty string (''). It can be used for styling anchor (link) elements.


K. 🧲 sticky

Ad-rotator.js permits you to display sticky Ads. These are ads that stay visible on the screen even when you scroll. By default, this setting is disabled, but you can enable it by simply passing an empty object. (sticky: {}).

You can also configure sticky advertisements in a way which ensures that your Ads are not intrusive and that they do not degrade user experience.

<!-- Include assets -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ad-rotator/dist/style.css" />
<script src="https://cdn.jsdelivr.net/npm/ad-rotator"></script>

<!-- example markup -->
<main class="start">Main Content</main>
<div>
  <div id="publicity">Ad area</div>
  <section class="middle">Middle content</section>
</div>
<footer class="end">Footer content</footer>

<hr/>
Ad-rotator.js
/* Example Styling  */
#publicity { /* style Ad-unit */
  height: 250px;
  width: 300px;
  background-color: yellow;
  overflow: hidden;
  margin: 20px 0;
}
.start, .end {    /* element before the Ad-unit */
  height: 200px;
  width: 100%;
  background-color: green;
}
.middle {    /* empty area */
  min-height: 1000px;
  width: 100%;
}
img {
  object-fit: cover;
  height: 100%;
  width: 100%;
}
// initialize ad-rotator
const instance = rotator(
  document.getElementById('publicity'),
  getAds(),
  {
    // sticky: {}, // this enables stickiness, but we recommend the config below:
    sticky: {
      beforeEl: document.querySelector('.start'),
      afterEl: document.querySelector('.end'),
      position: 'sticky',     // default - 'fixed'
      offsetTop: '20',        // or '20px' (defaults to 0px)
      offsetBottom: '100px',  // or '100' (defaults to 0px)
      noMobile: true          // disable stickiness on mobile (default - false)
    },
  }
);

// start the rotation
instance.start();

// ads
function getAds() {
  return [
    { url: 'https://fusionplatter.eu#1', img: 'https://niketpathak.com/images/works/gkm_pic_sq.jpg'},
    { url: 'https://digitalfortress.tech#2', img: 'https://niketpathak.com/images/works/maestrobits_sq.jpg'},
    { url: 'https://gospelmusic.io#3', img: 'https://niketpathak.com/images/works/halcyonminds_sq.jpg'}
  ];
}

The sticky config option can be customized by providing an Object with properties listed below -

  1. beforeEl: HTMLElement - refers to the Element from where the Ad becomes sticky. This means that the Ad becomes sticky only when you scroll upto this element. The default behaviour is to make the Ad sticky as soon as the user scrolls.
  2. afterEl: HTMLElement - refers to the Element from where the Ad stops being sticky. i.e. when you scroll to/after this element, the Ad will no longer be sticky. By default, the Ad stays sticky permanently.
  3. position: "fixed" | "sticky" - refers to the positioning to be used. By default, fixed positioning is used. When using sticky positioning, the beforeEl, afterEl and offsetBottom options have no effect.
  4. offsetTop: number | string - A margin that is added at the top of the Ad. Defaults to 0 i.e. sticks to the top of the screen.
  5. offsetBottom: number | string - A margin that is added at the bottom of the Ad. Defaults to 0.
  6. noMobile: Boolean - This option can be used when you wish for your Ad unit to not be sticky on a mobile. Its default value is false, meaning that the Ad will be sticky on all devices.

Another complete example showcasing sticky Ads can be found on the Playground.


Next
API
Previous
Usage