main/PromoBanner.js

import customEvent from '../utils/customEvent';
import InView from '../utils/classes/InView';

/**
 * Promo Banner Widget
 *
 * @module PromoBanner
 * @prop {object} selectors - DOM selector
 * @prop {object} css - css classes
 */
const PromoBanner = {
	selectors: {
		trackableBanner: '.c-promoBanners__item[data-tracking-pixel]',
	},

	css: {
		pixel: 'c-promoBanners__pixel',
	},

	/**
	 * Listen to in view event to trigger promo banner impression tracking pixel.
	 *
	 * @method init
	 */
	init() {
		const $targets = document.querySelectorAll( this.selectors.trackableBanner );

		if ( $targets.length > 0 ) {
			const watcher = new InView({
				threshold: 0.1,
				rootMargin: `${window.innerHeight * 0.4}px`,
			});
			watcher.init();

			[].forEach.call( $targets, ( $target ) => {
				$target.addEventListener( customEvent.IN_VIEW, ( event ) => {
					if ( event && event.detail && event.detail.isInView ) {
						watcher.stopWatching( $target );
						this.trackImpression( $target );
					}
				});
				watcher.startWatching( $target );
			});
		}
	},

	/**
	 * Fire tracking pixel of a promo banner
	 *
	 * @method trackImpression
	 */
	trackImpression( $target ) {
		const $trackingPixel = document.createElement( 'iframe' );
		const trackingPixel = $target.dataset.trackingPixel.replace( '%TIMESTAMP%', ( new Date() ).getTime() );
		$trackingPixel.setAttribute( 'src', trackingPixel );
		$trackingPixel.classList.add( this.css.pixel );
		$target.appendChild( $trackingPixel );
	},
};

export default PromoBanner;