grids.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * Javascript-Equal-Height-Responsive-Rows
  3. * https://github.com/Sam152/Javascript-Equal-Height-Responsive-Rows
  4. */
  5. (function($) {
  6. 'use strict';
  7. /**
  8. * Set all elements within the collection to have the same height.
  9. */
  10. $.fn.equalHeight = function() {
  11. var heights = [];
  12. $.each(this, function(i, element) {
  13. var $element = $(element);
  14. var elementHeight;
  15. // Should we include the elements padding in it's height?
  16. var includePadding = ($element.css('box-sizing') === 'border-box') || ($element.css('-moz-box-sizing') === 'border-box');
  17. if (includePadding) {
  18. elementHeight = $element.innerHeight();
  19. } else {
  20. elementHeight = $element.height();
  21. }
  22. heights.push(elementHeight);
  23. });
  24. this.css('height', Math.max.apply(window, heights) + 'px');
  25. return this;
  26. };
  27. /**
  28. * Create a grid of equal height elements.
  29. */
  30. $.fn.equalHeightGrid = function(columns) {
  31. var $tiles = this.filter(':visible');
  32. $tiles.css('height', 'auto');
  33. for (var i = 0; i < $tiles.length; i++) {
  34. if (i % columns === 0) {
  35. var row = $($tiles[i]);
  36. for (var n = 1; n < columns; n++) {
  37. row = row.add($tiles[i + n]);
  38. }
  39. row.equalHeight();
  40. }
  41. }
  42. return this;
  43. };
  44. /**
  45. * Detect how many columns there are in a given layout.
  46. */
  47. $.fn.detectGridColumns = function() {
  48. var offset = 0,
  49. cols = 0,
  50. $tiles = this.filter(':visible');
  51. $tiles.each(function(i, elem) {
  52. var elemOffset = $(elem).offset().top;
  53. if (offset === 0 || elemOffset === offset) {
  54. cols++;
  55. offset = elemOffset;
  56. } else {
  57. return false;
  58. }
  59. });
  60. return cols;
  61. };
  62. /**
  63. * Ensure equal heights now, on ready, load and resize.
  64. */
  65. var grids_event_uid = 0;
  66. $.fn.responsiveEqualHeightGrid = function() {
  67. var _this = this;
  68. var event_namespace = '.grids_' + grids_event_uid;
  69. _this.data('grids-event-namespace', event_namespace);
  70. function syncHeights() {
  71. var cols = _this.detectGridColumns();
  72. _this.equalHeightGrid(cols);
  73. }
  74. $(window).bind('resize' + event_namespace + ' load' + event_namespace, syncHeights);
  75. syncHeights();
  76. grids_event_uid++;
  77. return this;
  78. };
  79. /**
  80. * Unbind created events for a set of elements.
  81. */
  82. $.fn.responsiveEqualHeightGridDestroy = function() {
  83. var _this = this;
  84. _this.css('height', 'auto');
  85. $(window).unbind(_this.data('grids-event-namespace'));
  86. return this;
  87. };
  88. })(window.jQuery);