Ad-rotator
![Donate](https://img.shields.io/badge/Donate-PayPal-blue.svg?logo=paypal)
A fast, light-weight and highly configurable JS library to rotate advertisements.
🌟 Features 🌟
- 📦 Has 0 DEPENDENCIES! Written in pure JS (typescript).
- 🖼 Display native advertisements to adblock users
- 🔥 A super light-weight library, only
![<3Kb minzipped](https://img.shields.io/bundlephobia/minzip/ad-rotator)
- 📳 Supports completely responsive multiple ad instances customizable to the very pixel
- 💻 Display device specific ads i.e. ads targeted towards mobile/desktop
- 🪝 Provides hooks/callbacks that can be used for analytics, statistics, logging, etc...
- 🧲 Built-in support for sticky advertisements
- ⚖️ Assign weight/priority to Ad unit(s) to increase its chances of being shown
- ⚜️ Has a Fallback Mode i.e. kicks in only when your primary Ad network fails (for example, due to an Adblocker)
- 🌐 Supports every major browser!
- 🎀 Framework agnostic, free and open source
✨ Demo
Here is a Live Demo of Ad-rotation in action. You will find live examples that can tinkered with to get a clearer picture about what you could expect from this library.
# you can install ad-rotator with npm
$ npm install --save ad-rotator
# Alternatively you can use Yarn or PNPM
$ yarn add ad-rotator
$ pnpm add ad-rotator
Then include the library in your App/Page.
As a module,
import { init, stickyEl } from 'ad-rotator';
import 'ad-rotator/dist/style.css';
const rotator = require('ad-rotator');
require('ad-rotator/dist/style.css');
In the browser context,
<script src="./node_modules/ad-rotator/dist/rotator.umd.js"></script>
<link rel="stylesheet" href="./node_modules/ad-rotator/dist/style.css" />
<script src="https://cdn.jsdelivr.net/npm/ad-rotator"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ad-rotator/dist/style.css" />
<script src="https://unpkg.com/ad-rotator@5.8.0/dist/ad-rotator.js"></script>
<link rel="stylesheet" href="https://unpkg.com/ad-rotator@5.8.0/dist/style.css" />
The library will be available as a global object at window.rotator
🔧 Configuration
Ad-rotator.js requires 2 mandatory parameters to be setup. A 3rd optional parameter can be provided to override default values.
DOM element
(required) - A container Element where the Ads should be displayedArray
(required) - An Array of Advertisements([{url: '', img: ''},...]
) to be displayed. Each advertisement is expected to be an object with 2 mandatory properties img
and url
Details & Example of an Array of Ads
img
(required) - Its value can be an absolute URL, a relative URL or even a base-64 encoded image.url
(required) - It is the target url where the end-user will be directed on clicking the Ad.weight
(optional) - This property behaves differently depending on whether you are using sequential/random rotation. For sequential rotation, ads will be sorted by weight i.e. highest weight to the lowest weight. For random Ad rotation, weight adds a priority to each item. The higher the weight, the higher the chances of that Ad being shown first.title
(optional) - This property can be used to provide a small text describing the image/Ad. It is used to improve accessibility via aria-attributes and also to improve SEO.
let items = [
{img: './assets/image.jpg', url: 'https://xyz.com#1', title: 'Ad 1'},
{img: 'https://xyz.com/image.png', url: 'https://xyz.com#2', weight: 5},
{img: 'https://xyz.com/image.svg', url: 'https://xyz.com#3', weight: 10},
{img: 'data:image/jpeg;base64,/9j/4AAQSkZJRg...', url: 'https...'}
]
Object
(optional) - An Object with custom configuration options to override default values. (See all configuration options
)
🌱 Usage
In Html, create an Element. This element will be used as a container to inject Ads.
<div id="containerElement"></div>
In CSS, provide a size to your container Element. Also, set img
elements to 100% height/width to ensure they fill the container.
#containerElement {
height: 300px;
width: 250px;
}
img {
height: 100%;
width: 100%;
}
Using the above styles, the displayed Ads will have a height of 300px
and width of 250px
. Ad sizes are completely controlled by the user. You are free to use media queries to further tweak the dimensions.
See common sizes for responsive Ads to see Ad-dimensions that suit your needs.
In JS, create an Array
with the advertisements to be displayed.
let items = [
{ url: 'https://niketpathak.com#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'}
];
Then Initialize adRotator by passing the DOM Element
and the Array
of advertisements as parameters
const instance = rotator.init(
document.getElementById('containerElement'),
items
);
instance.start();
That's it! You should now have Ad-rotation in action! The library sets sensible defaults on initialization. For example, Ads are rotated in a random fashion by default. You can provide a 3rd optional configuration parameter to override this and fine tune the settings of your adrotator. See configuration options
for available variations.
NOTE: By default, adRotator
is designed to fail silently for any configuration error. This means that it will neither pollute the DOM nor will it attach any events in case of an error. It only logs a console error to help you diagnose any configuration error.
🎨 Styling (css)
In addition to the styling required for setting the dimensions of an Ad-unit, it is strongly recommended that you include the following base styles, however this is not mandatory. (Note: You may have included them already if you followed the steps in the install section)
.fadeIn {
-webkit-animation: fadeIn 200ms ease-in-out;
animation: fadeIn 200ms ease-in-out;
}
@-webkit-keyframes fadeIn {
from {
opacity: 0;
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
}
.stickyElx {
transition: all 0.5s;
z-index: 1;
}
These styles are optional and can be omitted or can be easily overriden as needed.
Ad-rotator accepts the following configuration options and all of them are Optional.
Parameter | Description | Default |
---|
timer? : number | The time after which an advertisement will be rotated in seconds. Lowest accepted value is 2s | 5 (seconds) |
target? : string | The target device. Can be set to desktop , mobile or all . When set to desktop, ads will be shown only on a desktop device whereas when set to mobile, ads will be displayed on a mobile device alone. By default, ads are shown on all devices. | "all" |
cb?: (unit: AdUnit, El: HTMLElement, conf: AdConfig) | A callback that is executed on every image rotation. The callback receives 3 parameters cb(currentAdUnit, parentElement, configParams) . This callback can be used for analytics, to programmatically control the rotator instance or for any other purpose. | undefined |
onHover?: (item: AdUnit, El: HTMLElement) | A callback that is executed on hovering over an Ad unit. The callback receives 2 parameters cb(currentAdUnit, parentElement) . | undefined |
onClick?: (e: MouseEvent, unit: AdUnit) | A callback that is executed on clicking an Ad unit. The callback receives 2 parameters (event, currentAdUnit) | undefined |
imgClass? : string | Class that should be added to the image Tag | "" |
linkClass? : string | Class that should be added to the link Tag | "" |
random? : boolean | The advertisements are rotated in a random fashion by default. Set to false to have them rotated sequentially | true |
newTab? : boolean | Set to true to open the advertisement URL in a new Tab | false |
fallbackMode? : boolean | Sets the working mode of the library. When set to true , the library is used only if it detects an Adblocker, otherwise it does absolutely nothing i.e. it neither pollutes the DOM nor attaches any events | false |
sticky? : {} | Allows sticky Ads. By default, Ads shown are not sticky. To enable sticky Ads, pass an empty object sticky: {} . You can customize sticky Ads by providing the following properties - | undefined |
sticky: {
beforeEl: document.querySelector('.start'),
afterEl: document.querySelector('.end'),
position: 'sticky',
offsetTop: '10',
offsetBottom: '150px',
noMobile: true
}
A css class stickyElx
is added dynamically to the sticky Element's container to allow further customization such as modifying css properties (like z-index), using media queries and so on.
💡 Note
It is possible to change configuration options after instantiation.
const instance = rotator( )
instance.conf.random = false;
💠 API
Starts the Ad-Rotation
const instance = rotator(
document.getElementById('containerElement'),
[
{ url: 'https://gospelmusic.io#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'}
],
{ target: 'mobile' }
);
instance.start();
Pauses the Rotation. However, if the user clicks/hovers the Ad or scrolls away from the Ad such that it is not visible anymore & then scrolls back to it, rotation will resume automatically. Rotation cannot be paused permanently because that would beat the purpose of this library.
const instance = rotator( )
instance.pause();
instance.conf.cb = instance.pause;
See cb(callback) config option for further details on its usage.
To resume the rotation, simply call adRotatorInstance.resume()
Resumes the Rotation.
const instance = rotator( )
instance.pause();
instance.resume();
Use adRotatorInstance.resume()
to resume a paused rotation.
Inject a new Advertisement into the adRotator.
const instance = rotator( )
instance.add(
{
url: 'https://gospelmusic.io',
img: './path-to-img'
}
);
The newly injected Advertisement will be displayed in the next rotation cycle
Remove an item from the Advertisements array.
const instance = rotator( )
instance.remove();
instance.remove(
{
url: 'https://digitalfortress.tech',
img: './path-to-img'
}
);
The remove()
method deletes the last item in the advertisements array. To remove a particular advertisement, you can also pass it a parameter (rotatorInstance.remove({ img: 'xyz.gif'})
). The change in the Advertisements array will be reflected in the next rotation cycle
Destroys Ad Rotation. Cleans up the DOM and removes all associated events.
const instance = rotator( )
instance.destroy();
To reactivate adRotator, simply call adRotatorInstance.start()
🧑💻 Contribute
Interested in contributing features and fixes?
Read more on contributing.
📝 Changelog
See the Changelog
📄 License
MIT © DigitalFortress