Last active
August 29, 2015 14:08
-
-
Save nekman/cfc11f6c01e5a53f7ab2 to your computer and use it in GitHub Desktop.
Timer + IFrameHeightResizer + BaconIpsum: http://plnkr.co/edit/lcpbkXBe1faNsgUu2nUQ?p=preview
This file contains 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
/* | |
* Timer | |
*/ | |
function Timer(callback, interval) { | |
this.nextTick = window.requestAnimationFrame || window.setTimeout; | |
this.interval = interval || 50; | |
this.callback = callback; | |
} | |
Timer.prototype.start = function() { | |
var self = this; | |
// Use setTimeout for adjusting frame rate. | |
// http://creativejs.com/resources/requestanimationframe/ | |
this.timer = setTimeout(function() { | |
self.start(); | |
self.callback && self.callback(); | |
}, this.interval); | |
return this; | |
}; | |
Timer.prototype.stop = function() { | |
clearTimeout(this.timer); | |
return this; | |
}; | |
/* | |
* IFrameHeightResizer | |
*/ | |
function IFrameHeightResizer(iframe) { | |
this.iframe = iframe; | |
this.oldHeight = 0; | |
this.timer = new Timer(this.check.bind(this)).start(); | |
this.check(); | |
} | |
IFrameHeightResizer.prototype.check = function() { | |
// https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements | |
var newHeight = this.iframe.contentWindow.document.body.scrollHeight; | |
if (newHeight !== this.oldHeight) { | |
this.adjust(newHeight); | |
} | |
}; | |
IFrameHeightResizer.prototype.adjust = function(newHeight) { | |
console.log('adjust from %d to %d', this.oldHeight, newHeight); | |
this.oldHeight = newHeight; | |
this.iframe.style.height = this.oldHeight + 'px'; | |
}; | |
/* | |
* BaconIpsum | |
*/ | |
function BaconIpsum(iframe) { | |
this.iframe = iframe; | |
this.url = 'http://baconipsum.com/api/?callback=?'; | |
this.params = { | |
type: 'meat-and-filler', | |
paras: 3 | |
}; | |
new Timer(this.fetch.bind(this), 5000).start(); | |
} | |
BaconIpsum.prototype.fetch = function() { | |
var self = this; | |
this.params.paras = Math.floor(Math.random() * 10) + 1; | |
$.getJSON(this.url, this.params).then(function(data) { | |
console.log('fetch', data); | |
self.iframe.contentWindow.document.body.innerHTML = data.join(); | |
}); | |
}; | |
// Start | |
document.addEventListener('DOMContentLoaded', function() { | |
var iframe = document.querySelector('iframe'); | |
// Check contents in iframe | |
new IFrameHeightResizer(iframe); | |
// Get BaconIpsum text each 5 sec. | |
new BaconIpsum(iframe); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment