jquery.columnizer.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. // version 1.6.0
  2. // http://welcome.totheinter.net/columnizer-jquery-plugin/
  3. // created by: Adam Wulf @adamwulf, adam.wulf@gmail.com
  4. (function($){
  5. $.fn.columnize = function(options) {
  6. var defaults = {
  7. // default width of columns
  8. width: 400,
  9. // optional # of columns instead of width
  10. columns : false,
  11. // true to build columns once regardless of window resize
  12. // false to rebuild when content box changes bounds
  13. buildOnce : false,
  14. // an object with options if the text should overflow
  15. // it's container if it can't fit within a specified height
  16. overflow : false,
  17. // this function is called after content is columnized
  18. doneFunc : function(){},
  19. // if the content should be columnized into a
  20. // container node other than it's own node
  21. target : false,
  22. // re-columnizing when images reload might make things
  23. // run slow. so flip this to true if it's causing delays
  24. ignoreImageLoading : true,
  25. // should columns float left or right
  26. columnFloat : "left",
  27. // ensure the last column is never the tallest column
  28. lastNeverTallest : false,
  29. // (int) the minimum number of characters to jump when splitting
  30. // text nodes. smaller numbers will result in higher accuracy
  31. // column widths, but will take slightly longer
  32. accuracy : false,
  33. // don't automatically layout columns, only use manual columnbreak
  34. manualBreaks : false,
  35. // previx for all the CSS classes used by this plugin
  36. // default to empty string for backwards compatibility
  37. cssClassPrefix : ""
  38. };
  39. var options = $.extend(defaults, options);
  40. if(typeof(options.width) == "string"){
  41. options.width = parseInt(options.width);
  42. if(isNaN(options.width)){
  43. options.width = defaults.width;
  44. }
  45. }
  46. return this.each(function() {
  47. var $inBox = options.target ? $(options.target) : $(this);
  48. var maxHeight = $(this).height();
  49. var $cache = $('<div></div>'); // this is where we'll put the real content
  50. var lastWidth = 0;
  51. var columnizing = false;
  52. var manualBreaks = options.manualBreaks;
  53. var cssClassPrefix = defaults.cssClassPrefix;
  54. if(typeof(options.cssClassPrefix) == "string"){
  55. cssClassPrefix = options.cssClassPrefix;
  56. }
  57. var adjustment = 0;
  58. $cache.append($(this).contents().clone(true));
  59. // images loading after dom load
  60. // can screw up the column heights,
  61. // so recolumnize after images load
  62. if(!options.ignoreImageLoading && !options.target){
  63. if(!$inBox.data("imageLoaded")){
  64. $inBox.data("imageLoaded", true);
  65. if($(this).find("img").length > 0){
  66. // only bother if there are
  67. // actually images...
  68. var func = function($inBox,$cache){ return function(){
  69. if(!$inBox.data("firstImageLoaded")){
  70. $inBox.data("firstImageLoaded", "true");
  71. $inBox.empty().append($cache.children().clone(true));
  72. $inBox.columnize(options);
  73. }
  74. }}($(this), $cache);
  75. $(this).find("img").one("load", func);
  76. $(this).find("img").one("abort", func);
  77. return;
  78. }
  79. }
  80. }
  81. $inBox.empty();
  82. columnizeIt();
  83. if(!options.buildOnce){
  84. $(window).resize(function() {
  85. if(!options.buildOnce && $.browser.msie){
  86. if($inBox.data("timeout")){
  87. clearTimeout($inBox.data("timeout"));
  88. }
  89. $inBox.data("timeout", setTimeout(columnizeIt, 200));
  90. }else if(!options.buildOnce){
  91. columnizeIt();
  92. }else{
  93. // don't rebuild
  94. }
  95. });
  96. }
  97. function prefixTheClassName(className, withDot){
  98. var dot = withDot ? "." : "";
  99. if(cssClassPrefix.length){
  100. return dot + cssClassPrefix + "-" + className;
  101. }
  102. return dot + className;
  103. }
  104. /**
  105. * this fuction builds as much of a column as it can without
  106. * splitting nodes in half. If the last node in the new column
  107. * is a text node, then it will try to split that text node. otherwise
  108. * it will leave the node in $pullOutHere and return with a height
  109. * smaller than targetHeight.
  110. *
  111. * Returns a boolean on whether we did some splitting successfully at a text point
  112. * (so we know we don't need to split a real element). return false if the caller should
  113. * split a node if possible to end this column.
  114. *
  115. * @param putInHere, the jquery node to put elements into for the current column
  116. * @param $pullOutHere, the jquery node to pull elements out of (uncolumnized html)
  117. * @param $parentColumn, the jquery node for the currently column that's being added to
  118. * @param targetHeight, the ideal height for the column, get as close as we can to this height
  119. */
  120. function columnize($putInHere, $pullOutHere, $parentColumn, targetHeight){
  121. //
  122. // add as many nodes to the column as we can,
  123. // but stop once our height is too tall
  124. while((manualBreaks || $parentColumn.height() < targetHeight) &&
  125. $pullOutHere[0].childNodes.length){
  126. var node = $pullOutHere[0].childNodes[0]
  127. //
  128. // Because we're not cloning, jquery will actually move the element"
  129. // http://welcome.totheinter.net/2009/03/19/the-undocumented-life-of-jquerys-append/
  130. if($(node).find(prefixTheClassName("columnbreak", true)).length){
  131. //
  132. // our column is on a column break, so just end here
  133. return;
  134. }
  135. if($(node).hasClass(prefixTheClassName("columnbreak"))){
  136. //
  137. // our column is on a column break, so just end here
  138. return;
  139. }
  140. $putInHere.append(node);
  141. }
  142. if($putInHere[0].childNodes.length == 0) return;
  143. // now we're too tall, so undo the last one
  144. var kids = $putInHere[0].childNodes;
  145. var lastKid = kids[kids.length-1];
  146. $putInHere[0].removeChild(lastKid);
  147. var $item = $(lastKid);
  148. //
  149. // now lets try to split that last node
  150. // to fit as much of it as we can into this column
  151. if($item[0].nodeType == 3){
  152. // it's a text node, split it up
  153. var oText = $item[0].nodeValue;
  154. var counter2 = options.width / 18;
  155. if(options.accuracy)
  156. counter2 = options.accuracy;
  157. var columnText;
  158. var latestTextNode = null;
  159. while($parentColumn.height() < targetHeight && oText.length){
  160. var indexOfSpace = oText.indexOf(' ', counter2);
  161. if (indexOfSpace != -1) {
  162. columnText = oText.substring(0, oText.indexOf(' ', counter2));
  163. } else {
  164. columnText = oText;
  165. }
  166. latestTextNode = document.createTextNode(columnText);
  167. $putInHere.append(latestTextNode);
  168. if(oText.length > counter2 && indexOfSpace != -1){
  169. oText = oText.substring(indexOfSpace);
  170. }else{
  171. oText = "";
  172. }
  173. }
  174. if($parentColumn.height() >= targetHeight && latestTextNode != null){
  175. // too tall :(
  176. $putInHere[0].removeChild(latestTextNode);
  177. oText = latestTextNode.nodeValue + oText;
  178. }
  179. if(oText.length){
  180. $item[0].nodeValue = oText;
  181. }else{
  182. return false; // we ate the whole text node, move on to the next node
  183. }
  184. }
  185. if($pullOutHere.contents().length){
  186. $pullOutHere.prepend($item);
  187. }else{
  188. $pullOutHere.append($item);
  189. }
  190. return $item[0].nodeType == 3;
  191. }
  192. /**
  193. * Split up an element, which is more complex than splitting text. We need to create
  194. * two copies of the element with it's contents divided between each
  195. */
  196. function split($putInHere, $pullOutHere, $parentColumn, targetHeight){
  197. if($putInHere.contents(":last").find(prefixTheClassName("columnbreak", true)).length){
  198. //
  199. // our column is on a column break, so just end here
  200. return;
  201. }
  202. if($putInHere.contents(":last").hasClass(prefixTheClassName("columnbreak"))){
  203. //
  204. // our column is on a column break, so just end here
  205. return;
  206. }
  207. if($pullOutHere.contents().length){
  208. var $cloneMe = $pullOutHere.contents(":first");
  209. //
  210. // make sure we're splitting an element
  211. if($cloneMe.get(0).nodeType != 1) return;
  212. //
  213. // clone the node with all data and events
  214. var $clone = $cloneMe.clone(true);
  215. //
  216. // need to support both .prop and .attr if .prop doesn't exist.
  217. // this is for backwards compatibility with older versions of jquery.
  218. if($cloneMe.hasClass(prefixTheClassName("columnbreak"))){
  219. //
  220. // ok, we have a columnbreak, so add it into
  221. // the column and exit
  222. $putInHere.append($clone);
  223. $cloneMe.remove();
  224. }else if (manualBreaks){
  225. // keep adding until we hit a manual break
  226. $putInHere.append($clone);
  227. $cloneMe.remove();
  228. }else if($clone.get(0).nodeType == 1 && !$clone.hasClass(prefixTheClassName("dontend"))){
  229. $putInHere.append($clone);
  230. if($clone.is("img") && $parentColumn.height() < targetHeight + 20){
  231. //
  232. // we can't split an img in half, so just add it
  233. // to the column and remove it from the pullOutHere section
  234. $cloneMe.remove();
  235. }else if(!$cloneMe.hasClass(prefixTheClassName("dontsplit")) && $parentColumn.height() < targetHeight + 20){
  236. //
  237. // pretty close fit, and we're not allowed to split it, so just
  238. // add it to the column, remove from pullOutHere, and be done
  239. $cloneMe.remove();
  240. }else if($clone.is("img") || $cloneMe.hasClass(prefixTheClassName("dontsplit"))){
  241. //
  242. // it's either an image that's too tall, or an unsplittable node
  243. // that's too tall. leave it in the pullOutHere and we'll add it to the
  244. // next column
  245. $clone.remove();
  246. }else{
  247. //
  248. // ok, we're allowed to split the node in half, so empty out
  249. // the node in the column we're building, and start splitting
  250. // it in half, leaving some of it in pullOutHere
  251. $clone.empty();
  252. if(!columnize($clone, $cloneMe, $parentColumn, targetHeight)){
  253. // this node still has non-text nodes to split
  254. // add the split class and then recur
  255. $cloneMe.addClass(prefixTheClassName("split"));
  256. if($cloneMe.children().length){
  257. split($clone, $cloneMe, $parentColumn, targetHeight);
  258. }
  259. }else{
  260. // this node only has text node children left, add the
  261. // split class and move on.
  262. $cloneMe.addClass(prefixTheClassName("split"));
  263. }
  264. if($clone.get(0).childNodes.length == 0){
  265. // it was split, but nothing is in it :(
  266. $clone.remove();
  267. }
  268. }
  269. }
  270. }
  271. }
  272. function singleColumnizeIt() {
  273. if ($inBox.data("columnized") && $inBox.children().length == 1) {
  274. return;
  275. }
  276. $inBox.data("columnized", true);
  277. $inBox.data("columnizing", true);
  278. $inBox.empty();
  279. $inBox.append($("<div class='"
  280. + prefixTheClassName("first") + " "
  281. + prefixTheClassName("last") + " "
  282. + prefixTheClassName("column") + " "
  283. + "' style='width:100%; float: " + options.columnFloat + ";'></div>")); //"
  284. $col = $inBox.children().eq($inBox.children().length-1);
  285. $destroyable = $cache.clone(true);
  286. if(options.overflow){
  287. targetHeight = options.overflow.height;
  288. columnize($col, $destroyable, $col, targetHeight);
  289. // make sure that the last item in the column isn't a "dontend"
  290. if(!$destroyable.contents().find(":first-child").hasClass(prefixTheClassName("dontend"))){
  291. split($col, $destroyable, $col, targetHeight);
  292. }
  293. while($col.contents(":last").length && checkDontEndColumn($col.contents(":last").get(0))){
  294. var $lastKid = $col.contents(":last");
  295. $lastKid.remove();
  296. $destroyable.prepend($lastKid);
  297. }
  298. var html = "";
  299. var div = document.createElement('DIV');
  300. while($destroyable[0].childNodes.length > 0){
  301. var kid = $destroyable[0].childNodes[0];
  302. if(kid.attributes){
  303. for(var i=0;i<kid.attributes.length;i++){
  304. if(kid.attributes[i].nodeName.indexOf("jQuery") == 0){
  305. kid.removeAttribute(kid.attributes[i].nodeName);
  306. }
  307. }
  308. }
  309. div.innerHTML = "";
  310. div.appendChild($destroyable[0].childNodes[0]);
  311. html += div.innerHTML;
  312. }
  313. var overflow = $(options.overflow.id)[0];
  314. overflow.innerHTML = html;
  315. }else{
  316. $col.append($destroyable);
  317. }
  318. $inBox.data("columnizing", false);
  319. if(options.overflow && options.overflow.doneFunc){
  320. options.overflow.doneFunc();
  321. }
  322. }
  323. /**
  324. * returns true if the input dom node
  325. * should not end a column.
  326. * returns false otherwise
  327. */
  328. function checkDontEndColumn(dom){
  329. if(dom.nodeType == 3){
  330. // text node. ensure that the text
  331. // is not 100% whitespace
  332. if(/^\s+$/.test(dom.nodeValue)){
  333. //
  334. // ok, it's 100% whitespace,
  335. // so we should return checkDontEndColumn
  336. // of the inputs previousSibling
  337. if(!dom.previousSibling) return false;
  338. return checkDontEndColumn(dom.previousSibling);
  339. }
  340. return false;
  341. }
  342. if(dom.nodeType != 1) return false;
  343. if($(dom).hasClass(prefixTheClassName("dontend"))) return true;
  344. if(dom.childNodes.length == 0) return false;
  345. return checkDontEndColumn(dom.childNodes[dom.childNodes.length-1]);
  346. }
  347. function columnizeIt() {
  348. //reset adjustment var
  349. adjustment = 0;
  350. if(lastWidth == $inBox.width()) return;
  351. lastWidth = $inBox.width();
  352. var numCols = Math.round($inBox.width() / options.width);
  353. var optionWidth = options.width;
  354. var optionHeight = options.height;
  355. if(options.columns) numCols = options.columns;
  356. if(manualBreaks){
  357. numCols = $cache.find(prefixTheClassName("columnbreak", true)).length + 1;
  358. optionWidth = false;
  359. }
  360. // if ($inBox.data("columnized") && numCols == $inBox.children().length) {
  361. // return;
  362. // }
  363. if(numCols <= 1){
  364. return singleColumnizeIt();
  365. }
  366. if($inBox.data("columnizing")) return;
  367. $inBox.data("columnized", true);
  368. $inBox.data("columnizing", true);
  369. $inBox.empty();
  370. $inBox.append($("<div style='width:" + (Math.floor(100 / numCols))+ "%; float: " + options.columnFloat + ";'></div>")); //"
  371. $col = $inBox.children(":last");
  372. $col.append($cache.clone());
  373. maxHeight = $col.height();
  374. $inBox.empty();
  375. var targetHeight = maxHeight / numCols;
  376. var firstTime = true;
  377. var maxLoops = 3;
  378. var scrollHorizontally = false;
  379. if(options.overflow){
  380. maxLoops = 1;
  381. targetHeight = options.overflow.height;
  382. }else if(optionHeight && optionWidth){
  383. maxLoops = 1;
  384. targetHeight = optionHeight;
  385. scrollHorizontally = true;
  386. }
  387. //
  388. // We loop as we try and workout a good height to use. We know it initially as an average
  389. // but if the last column is higher than the first ones (which can happen, depending on split
  390. // points) we need to raise 'adjustment'. We try this over a few iterations until we're 'solid'.
  391. //
  392. // also, lets hard code the max loops to 20. that's /a lot/ of loops for columnizer,
  393. // and should keep run aways in check. if somehow someone has content combined with
  394. // options that would cause an infinite loop, then this'll definitely stop it.
  395. for(var loopCount=0;loopCount<maxLoops && maxLoops < 20;loopCount++){
  396. $inBox.empty();
  397. var $destroyable;
  398. try{
  399. $destroyable = $cache.clone(true);
  400. }catch(e){
  401. // jquery in ie6 can't clone with true
  402. $destroyable = $cache.clone();
  403. }
  404. $destroyable.css("visibility", "hidden");
  405. // create the columns
  406. for (var i = 0; i < numCols; i++) {
  407. /* create column */
  408. var className = (i == 0) ? prefixTheClassName("first") : "";
  409. className += " " + prefixTheClassName("column");
  410. var className = (i == numCols - 1) ? (prefixTheClassName("last") + " " + className) : className;
  411. $inBox.append($("<div class='" + className + "' style='width:" + (Math.floor(100 / numCols))+ "%; float: " + options.columnFloat + ";'></div>")); //"
  412. }
  413. // fill all but the last column (unless overflowing)
  414. var i = 0;
  415. while(i < numCols - (options.overflow ? 0 : 1) || scrollHorizontally && $destroyable.contents().length){
  416. if($inBox.children().length <= i){
  417. // we ran out of columns, make another
  418. $inBox.append($("<div class='" + className + "' style='width:" + (Math.floor(100 / numCols))+ "%; float: " + options.columnFloat + ";'></div>")); //"
  419. }
  420. var $col = $inBox.children().eq(i);
  421. columnize($col, $destroyable, $col, targetHeight);
  422. // make sure that the last item in the column isn't a "dontend"
  423. split($col, $destroyable, $col, targetHeight);
  424. while($col.contents(":last").length && checkDontEndColumn($col.contents(":last").get(0))){
  425. var $lastKid = $col.contents(":last");
  426. $lastKid.remove();
  427. $destroyable.prepend($lastKid);
  428. }
  429. i++;
  430. //
  431. // https://github.com/adamwulf/Columnizer-jQuery-Plugin/issues/47
  432. //
  433. // check for infinite loop.
  434. //
  435. // this could happen when a dontsplit or dontend item is taller than the column
  436. // we're trying to build, and its never actually added to a column.
  437. //
  438. // this results in empty columns being added with the dontsplit item
  439. // perpetually waiting to get put into a column. lets force the issue here
  440. if($col.contents().length == 0 && $destroyable.contents().length){
  441. //
  442. // ok, we're building zero content columns. this'll happen forever
  443. // since nothing can ever get taken out of destroyable.
  444. //
  445. // to fix, lets put 1 item from destroyable into the empty column
  446. // before we iterate
  447. $col.append($destroyable.contents(":first"));
  448. }else if(i == numCols - (options.overflow ? 0 : 1) && !options.overflow){
  449. //
  450. // ok, we're about to exit the while loop because we're done with all
  451. // columns except the last column.
  452. //
  453. // if $destroyable still has columnbreak nodes in it, then we need to keep
  454. // looping and creating more columns.
  455. if($destroyable.find(prefixTheClassName("columnbreak", true)).length){
  456. numCols ++;
  457. }
  458. }
  459. }
  460. if(options.overflow && !scrollHorizontally){
  461. var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
  462. var IE7 = (document.all) && (navigator.appVersion.indexOf("MSIE 7.") != -1);
  463. if(IE6 || IE7){
  464. var html = "";
  465. var div = document.createElement('DIV');
  466. while($destroyable[0].childNodes.length > 0){
  467. var kid = $destroyable[0].childNodes[0];
  468. for(var i=0;i<kid.attributes.length;i++){
  469. if(kid.attributes[i].nodeName.indexOf("jQuery") == 0){
  470. kid.removeAttribute(kid.attributes[i].nodeName);
  471. }
  472. }
  473. div.innerHTML = "";
  474. div.appendChild($destroyable[0].childNodes[0]);
  475. html += div.innerHTML;
  476. }
  477. var overflow = $(options.overflow.id)[0];
  478. overflow.innerHTML = html;
  479. }else{
  480. $(options.overflow.id).empty().append($destroyable.contents().clone(true));
  481. }
  482. }else if(!scrollHorizontally){
  483. // the last column in the series
  484. $col = $inBox.children().eq($inBox.children().length-1);
  485. while($destroyable.contents().length) $col.append($destroyable.contents(":first"));
  486. var afterH = $col.height();
  487. var diff = afterH - targetHeight;
  488. var totalH = 0;
  489. var min = 10000000;
  490. var max = 0;
  491. var lastIsMax = false;
  492. var numberOfColumnsThatDontEndInAColumnBreak = 0;
  493. $inBox.children().each(function($inBox){ return function($item){
  494. var $col = $inBox.children().eq($item);
  495. var endsInBreak = $col.children(":last").find(prefixTheClassName("columnbreak", true)).length;
  496. if(!endsInBreak){
  497. var h = $col.height();
  498. lastIsMax = false;
  499. totalH += h;
  500. if(h > max) {
  501. max = h;
  502. lastIsMax = true;
  503. }
  504. if(h < min) min = h;
  505. numberOfColumnsThatDontEndInAColumnBreak++;
  506. }
  507. }}($inBox));
  508. var avgH = totalH / numberOfColumnsThatDontEndInAColumnBreak;
  509. if(totalH == 0){
  510. //
  511. // all columns end in a column break,
  512. // so we're done here
  513. loopCount = maxLoops;
  514. }else if(options.lastNeverTallest && lastIsMax){
  515. // the last column is the tallest
  516. // so allow columns to be taller
  517. // and retry
  518. //
  519. // hopefully this'll mean more content fits into
  520. // earlier columns, so that the last column
  521. // can be shorter than the rest
  522. adjustment += 30;
  523. targetHeight = targetHeight + 30;
  524. if(loopCount == maxLoops-1) maxLoops++;
  525. }else if(max - min > 30){
  526. // too much variation, try again
  527. targetHeight = avgH + 30;
  528. }else if(Math.abs(avgH-targetHeight) > 20){
  529. // too much variation, try again
  530. targetHeight = avgH;
  531. }else {
  532. // solid, we're done
  533. loopCount = maxLoops;
  534. }
  535. }else{
  536. // it's scrolling horizontally, fix the width/classes of the columns
  537. $inBox.children().each(function(i){
  538. $col = $inBox.children().eq(i);
  539. $col.width(optionWidth + "px");
  540. if(i==0){
  541. $col.addClass(prefixTheClassName("first"));
  542. }else if(i==$inBox.children().length-1){
  543. $col.addClass(prefixTheClassName("last"));
  544. }else{
  545. $col.removeClass(prefixTheClassName("first"));
  546. $col.removeClass(prefixTheClassName("last"));
  547. }
  548. });
  549. $inBox.width($inBox.children().length * optionWidth + "px");
  550. }
  551. $inBox.append($("<br style='clear:both;'>"));
  552. }
  553. $inBox.find(prefixTheClassName("column", true)).find(":first" + prefixTheClassName("removeiffirst", true)).remove();
  554. $inBox.find(prefixTheClassName("column", true)).find(':last' + prefixTheClassName("removeiflast", true)).remove();
  555. $inBox.data("columnizing", false);
  556. if(options.overflow){
  557. options.overflow.doneFunc();
  558. }
  559. options.doneFunc();
  560. }
  561. });
  562. };
  563. })(jQuery);