Last active
September 7, 2015 15:52
-
-
Save prisme/c49311f8817530f6a779 to your computer and use it in GitHub Desktop.
Return pages of elements based on available space
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
/* | |
* | |
* Use: | |
* var pages = blocksToPages(myElement) | |
* returns array of elements. | |
* | |
*/ | |
define([ | |
], function() { | |
return function(element) { | |
var pages = []; | |
var availableHeight = element.parentNode.clientHeight; | |
var refDummy = element.cloneNode(true); | |
var blocks = refDummy.children; | |
// Our element for injecting content and performing experiments upon. | |
var test = element.cloneNode(false); | |
element.parentNode.appendChild(test); | |
var index = 0; | |
while (blocks.length > 0) { | |
// Move next block to test element | |
test.appendChild(blocks[0]); | |
if (test.clientHeight > availableHeight) { | |
// Too big, put it back | |
refDummy.insertBefore(test.lastChild, refDummy.firstChild); | |
// Store page | |
pages.push(test); | |
// Remove test element | |
test.parentNode.removeChild(test); | |
// Avoid infinite | |
if (test.children.length === 0) { | |
console.log('Space too small'); | |
return []; | |
} | |
// Create next page | |
test = element.cloneNode(false); | |
element.parentNode.appendChild(test); | |
} | |
} | |
// Store last page | |
pages.push(test); | |
// Remove test element | |
test.parentNode.removeChild(test); | |
return pages; | |
}; | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment