bux23
6/26/2017 - 1:35 PM

Tiny masonry with fadein

Tiny masonry with fadein

function TinyMasonry(el) {
  var self = this
  var columns = []
  var lastKnownIndex = 0

  function createColumns(n) {
    var width = 100 / n + "%"
    columns = []
    while (n--) {
      var column = document.createElement("div")
      column.style.width = width
      column.style.float = "left"
      el.appendChild(column)
      columns.push(column)
    }
  }

  function getShortest() {
    var shortest = columns[0]
    for (var i = columns.length; i--;) {
      if (columns[i].clientHeight <= shortest.clientHeight) {
        shortest = columns[i]
      }
    }
    return shortest
  }

  function layout(tested) {
    var width = tested.parentElement.clientWidth / tested.clientWidth
    var n = Math.min(42, Math.round(width)) || 1
    var child
    while (child = el.firstElementChild) {
      child.parentNode.removeChild(child)
    }
    el.style.overflow = "hidden"
    createColumns(n)
    self.items.forEach(function(item,index) {
      item.style.display = "block"
      item.style.width = "auto"
      item.style.visibility = ""
      getShortest().appendChild(item)
      setTimeout(function() {
        item.classList.remove('op0')
      }, (100 * (index + 1)));

    })
    el.style.minHeight = ""
  }

  self.update = function() {
    
    self.items.slice(lastKnownIndex + 1).forEach(function(item,index) {
          item.classList.add('op0')
    })
  
    if (self.items[0]) {
      el.classList.add("tinyMasonryLoaded")
      if (columns[0]) {
        el.style.minHeight = el.clientHeight + "px"
      }
      var tested = self.items[0]
      tested.style.width = ""
      if (tested.parentNode && tested.parentNode.parentNode === el) {
        layout(tested)
      } else {
        el.appendChild(tested)
        setTimeout(layout.bind(0, tested))
      }
    }
    
    lastKnownIndex = self.items.length - 1
  }

  self.items = [].slice.call(el.children)
  self.update()

  var resizer;
  var startWidth = window.innerWidth;

  function resizeTimeout() {
      clearTimeout(resizer);
      resizer = setTimeout(doneResizing, 100)
  } 

  function doneResizing() {
    var curWidth = window.innerWidth;
    var breakpoint = false;
      if ((startWidth >= 580 && curWidth < 580) || (startWidth <= 580 && curWidth > 580)) {
          breakpoint = true
      }
      else if ((startWidth >= 980 && curWidth < 980) || (startWidth <= 980 && curWidth > 980)) {
          breakpoint = true
      }
      if(breakpoint === true) {
          self.items.forEach(function(item,index) {
            item.classList.add('op0')
          })
          self.update()
      }
      startWidth = window.innerWidth;
  }

  window.addEventListener("resize", resizeTimeout)
}

if (typeof exports === "object") {
  module.exports = TinyMasonry
}