Last active
September 21, 2020 08:39
-
-
Save yaquawa/b23cf060016b0c530fd2577d2b6c6dc3 to your computer and use it in GitHub Desktop.
Fluid Ad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
# Usage | |
1. Place this script anywhere after your gpt tag. | |
2. Add class `js-gpt-fluid-size` to your slot element. | |
# Notice | |
This script require jQuery to be installed, | |
but you can place this script before jQuery if you want. | |
*/ | |
(function () { | |
function Queue(listener, waitFor) { | |
this.queue = []; | |
this.listener = listener; | |
this.waitFor = waitFor; | |
this.wait = window[waitFor] === undefined; | |
if (this.wait) { | |
this.searchWaitFor(); | |
} | |
} | |
Queue.prototype.handleQueuedItems = function () { | |
while (this.queue.length) { | |
this.listener(this.queue.shift()); | |
} | |
}; | |
Queue.prototype.searchWaitFor = function () { | |
if (window[this.waitFor] !== undefined) { | |
this.handleQueuedItems(); | |
this.wait = false; | |
return; | |
} | |
var self = this; | |
setTimeout(function () { | |
self.searchWaitFor(); | |
}, 100); | |
}; | |
Queue.prototype.push = function (item) { | |
if (this.wait) { | |
this.queue.push(item); | |
return this; | |
} | |
this.listener(item); | |
}; | |
function autoResizeAdIframe() { | |
var slots = new Queue(resizeSlot, 'jQuery'); | |
googletag.cmd.push(function () { | |
googletag.pubads().addEventListener('slotRenderEnded', function (event) { | |
slots.push(event.slot); | |
}); | |
}); | |
function resizeSlot(slot) { | |
var $ = window.jQuery, | |
$win = $(window), | |
$slotElement = $(document.getElementById(slot.getSlotElementId())); | |
if (!$slotElement.hasClass('js-gpt-fluid-size')) { | |
return; | |
} | |
var resizeWindow = makeWindowResizeHandler($slotElement); | |
resizeWindow(); | |
$win.on('resize', resizeWindow); | |
} | |
function makeWindowResizeHandler($slotElement) { | |
var $iframe = $slotElement.find('iframe'), | |
aspect_ratio = $iframe.width() / $iframe.height(); | |
// remove width and height style of the wrapper div | |
$iframe.parent().attr('style', null); | |
// make iframe fluid | |
$iframe.css('width', '100%'); | |
return function () { | |
$iframe.height(Math.ceil($slotElement.width() / aspect_ratio)); | |
}; | |
} | |
} | |
autoResizeAdIframe(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment