Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="app"></div>
              
            
!

CSS

              
                // customize styles:
html {
  overflow-y: scroll;
}
body {
  background-color: #f3f5f6;
}

#app {
  width: 100%;
  padding: 10px;
  @media screen and (max-width: 550px) {
    padding: 0;
  }
}
.photo-grid-box {
  .photo-block {
    &__panel {
      &__title {
        position: absolute;
        color: #fff;
        padding : 10px;
        bottom: 0;
        background: #00000050;
        width: 100%;
      }
    }
  }
}

// phtot-grid-box original styles:
.photo-grid-box {
  position: relative;
  width: 100%;
  margin: 0px auto;
  background-color: #f3f5f6;
  .photo-block {
    display: inline-block;
    position: absolute;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: 50%;
    &--clickable {
      cursor: pointer;
    }
    &__panel{
      position: relative;
      width: 100%;
      height: 100%;
      opacity: 0;
      transition: opacity .3s;
      overflow: hidden;
    }
    &:hover {
      .photo-block {
        &__panel {
          opacity: 1;
        }  
      }      
    }
  }
}

              
            
!

JS

              
                /*
 * PhotoGridBox class
 */
function PhotoGridBox (insertPoint, imgs, imgOnClick, panelHTMLSetter, rowGap, colGap) {
  this.insertPoint = insertPoint
  this.imgLoader = new Image()
  this.dom = null
  this.imgs = []
  this.rowHeight = this._getRowHeight()
  this.rowGap = rowGap ? rowGap : 3
  this.colGap = colGap ? colGap : 3
  this.rowLength = 0
  this.showUnCompeleteRow = false
  this.compeleteIndex = -1  
  this.lastRenderedWindowOffsetWidth = window.innerWidth
  this.minImgWidth = this._getMinImgWidth()
 
  this._initDOM()
  if (imgOnClick) {
     this.imgOnClick = imgOnClick
  }
  if (panelHTMLSetter) {
    this.panelHTMLSetter = panelHTMLSetter
  }
  if (imgs) {
    this.appendImgs(imgs)
  }
}
PhotoGridBox.prototype._initDOM = function () {
  try {
    var uniqueClassName = 'photo-grid-box-' + +new Date()
    var className = 'photo-grid-box ' + uniqueClassName
    this.insertPoint.innerHTML = '<div class="'+ className +'"></div>'
    this.dom = document.querySelector('.' + uniqueClassName)
    this.dom.style.width = this.dom.offsetWidth + 'px'
  } catch (e) {
    console.error(e)
  }
}
PhotoGridBox.prototype._getRowHeight = function () {
  if (window.innerWidth <= 350) {
    return 200
  } else if (window.innerWidth <= 550) {
    return 250
  } else if (window.innerWidth <= 768) {
    return 270
  }
  return 280
}
PhotoGridBox.prototype._getMinImgWidth = function () {
  if (window.innerWidth <= 350) {
    return 130
  } else if (window.innerWidth <= 550) {
    return 150
  } else if (window.innerWidth <= 768) {
    return 180
  }
  return 200
}
PhotoGridBox.prototype.appendImgs = function (imgs) {
  if (Array.isArray(imgs) && imgs.length > 0) {
    var self = this
    imgs.map(function(img, index) {
      self.imgs.push(img)
    })
    this._render()
  } else {
    console.error('imgs should be an array with the elements of the src of the images(String).')
  }
}
PhotoGridBox.prototype._render = function () {
  var self = this
  if (!self.dom) self._initDOM()
  self._addWindowResizeEvent()
  var imgDOMs = document.querySelectorAll('.photo-block')
  var imgIndex = self.compeleteIndex + 1
  var imgsLength = self.imgs.length
  var imgLoader = self.imgLoader
  var tempRow = []
  var tempAccumulateWidth = 0
  imgLoader.onload = function () {
    var imgWidth = calcWidthByRowHeight(this.width, this.height)
    var imgAndGapWidth = imgWidth + self.colGap
    var element = createBlockElement(this.src, self.imgs[imgIndex], imgWidth, self.rowHeight, self.rowLength)
    var buffer = self.minImgWidth
    addElementToTempRow(element, imgAndGapWidth)
    if (tempAccumulateWidth + buffer >= self.dom.offsetWidth) {
      adjustImagesInTheRow()
      handleCompleteRow()
    }
    loadImage(++imgIndex, imgsLength)
  }
  imgLoader.onerror = function (e) {
    loadImage(++imgIndex, imgsLength)
  }
  loadImage(imgIndex, imgsLength)
  
  function loadImage(imgIndex, imgsLength) {
    removeIfImgBlockExist(imgIndex)
    if (imgIndex === imgsLength) {
      if (tempAccumulateWidth) {
        handleUnCompleteRow()
      }
      return
    }
    var imgSrc = self.imgs[imgIndex]
    if (imgSrc && typeof imgSrc === 'object') {
      if (imgSrc.src) {
        imgSrc = imgSrc.src
      } else {
        console.error('Invalid format: elements in imgs should be a string or an object with src attribute. Picture in index: ' + imgIndex + ' will not be shown.')
      }
    }
    imgLoader.src = imgSrc
  }
  function removeIfImgBlockExist(imgIndex) {
    if(imgDOMs[imgIndex]) {
      imgDOMs[imgIndex].remove()
    }
  }
  function calcWidthByRowHeight(width, height) {
    var ratio = self.rowHeight / height
    var result = Math.round(width * ratio)
    var buffer = 100
    if (result < self.minImgWidth + buffer) {
      result = self.minImgWidth
    }
    return result
  }
  function createBlockElement(imgSrc, imgConfig, imgWidth, imgHeight, rowIndex) {
    var element = document.createElement('div')
    var rowGap = self.rowGap * rowIndex
    var top = self.rowHeight * rowIndex + rowGap
    var left = tempAccumulateWidth
    element.style.backgroundImage = 'url('+ imgSrc +')'  
    element.className = 'photo-block'
    element.style.width = imgWidth + 'px'
    element.style.height = imgHeight + 'px'    
    element.style.top = top + 'px'
    element.style.left = left + 'px'
    if (self.imgOnClick) {
      element.onclick = function (e) {
        self.imgOnClick(e, imgConfig)
      }
      element.className += ' photo-block--clickable'
    }
    element.innerHTML = createBlockElementChildren(imgConfig)
    return element
  }
  function createBlockElementChildren(imgConfig) {
    var htmlString = '<div class="photo-block__panel">'
    if (self.panelHTMLSetter) {
      htmlString += self.panelHTMLSetter(imgConfig) 
    }
    htmlString += '</div>'
    return htmlString
  }
  function addElementToTempRow(element, imgAndGapWidth) {
    tempAccumulateWidth += imgAndGapWidth
    tempRow.push(element)
  }
  function adjustImagesInTheRow() {
    var pad = self.dom.offsetWidth - (tempAccumulateWidth - self.colGap)
    var adjustElementsIndex = []
    for (var i = 0; i < tempRow.length; i++) {
      if (pad > 0) {
        adjustElementsIndex.push(i)
      } else {
        var element = tempRow[i]
        var elementWidth = parseFloat(element.style.width.replace('px', ''))
        if (elementWidth > self.minImgWidth) {
          adjustElementsIndex.push(i)
        }
      }
    }
    var padPerBlock = pad / adjustElementsIndex.length
    var accumulateWidth = 0
    for (var i = 0; i < tempRow.length; i++) {
      var element = tempRow[i]
      var width = parseFloat(element.style.width.replace('px', ''))
      if (adjustElementsIndex.includes(i)) {
        width += padPerBlock
        element.style.width = width + 'px'
      }
      element.style.left = accumulateWidth + 'px'
      accumulateWidth += width + self.colGap
    }
  }
  function handleCompleteRow() {
    renderRow()
    resetTempForNextRow()
  }
  function handleUnCompleteRow() {
    if (self.showUnCompeleteRow || self.rowLength === 0) {
      renderRow(true)  
    }
    resetTempForNextRow()
  }
  function renderRow(isRowUnComplete) {
    var rowLength = 0
    if (!isRowUnComplete) {
      self.rowLength += 1
    } else {
      rowLength += 1
    }
    rowLength += self.rowLength
    var accumulateBlockHeight = self.rowHeight * rowLength + self.rowGap * (rowLength - 1)
    self.dom.style.height = parseFloat(accumulateBlockHeight) + 'px'
    tempRow.map(function(element) {
      self.dom.append(element)
      if (!isRowUnComplete) self.compeleteIndex += 1
    })
  }
  function resetTempForNextRow() {
    tempRow = []
    tempAccumulateWidth = 0
  }
}
PhotoGridBox.prototype.setImgOnClick = function (imgOnClick) {
  if (imgOnClick) {
    this.imgOnClick = imgOnClick    
  }
  this._rerender(this)
}
PhotoGridBox.prototype.setPanelHTMLSetter = function (panelHTMLSetter) {
  if (panelHTMLSetter) {
    this.panelHTMLSetter = panelHTMLSetter    
  }
  this._rerender(this)
}
PhotoGridBox.prototype.setShowUnCompleteRow = function (value) {
  if (typeof value === 'boolean') this.showUnCompeleteRow = value
}
PhotoGridBox.prototype._rerender = function (self) {
  this.rowLength = 0
  this.rowHeight = this._getRowHeight()
  this.minImgWidth = this._getMinImgWidth()
  this.compeleteIndex = -1
  self.dom.style.width = null
  this._render()
}
PhotoGridBox.prototype._addWindowResizeEvent = function () {
  if (this.isResizeEventAdded) return
  var self = this
  var delay = 300
  var timeout
  this._resizeEvent = function () {
    clearTimeout(timeout)
    timeout = setTimeout(function() {
      if (self.lastRenderedWindowOffsetWidth !== window.innerWidth) {
        self._rerender(self)
        self.lastRenderedWindowOffsetWidth = window.innerWidth
      }      
    }, delay)
  }
  window.addEventListener('resize', this._resizeEvent)
  this.isResizeEventAdded = true
}
PhotoGridBox.prototype._removeWindowResizeEvent = function () {
  window.removeEventListener('resize', this._resizeEvent)
  this.isResizeEventAdded = false
}
PhotoGridBox.prototype.destroy = function () {
  this._removeWindowResizeEvent()
  this.rowLength = 0
  this.compeleteIndex = -1
  this.dom.remove()
  this.dom = null
  this.imgs = []
}

/*
 * create object
 */
console.log('=======================')
var insertPoint = document.querySelector('#app')
var imgs = [
  {
    src: 'https://live.staticflickr.com/4513/37344511664_79f514815f_n.jpg',
    payload: {
      title: 'picture1'
    }
  },
  {
    src: 'https://live.staticflickr.com/4716/38433351710_0355b58068_z.jpg',
    payload: {
      title: 'picture2'
    }
  },
  'https://live.staticflickr.com/4703/25372643047_302849c0d0_z.jpg',
  'https://live.staticflickr.com/4753/38432660740_78d6d34d89_z.jpg',
  'https://live.staticflickr.com/4649/38432665780_71b232cc13_z.jpg',
  'https://live.staticflickr.com/4704/38432657930_c96c750753_z.jpg',
  'https://live.staticflickr.com/668/22838204747_bc4d056d61_z.jpg',
  'https://live.staticflickr.com/5648/22603412144_8bd9ba19bd_n.jpg',
  'https://live.staticflickr.com/5704/22410267477_303a090dcd_n.jpg',
  'https://live.staticflickr.com/683/22207558073_8ecdb7abc4_z.jpg',  
  'https://live.staticflickr.com/5156/14353130514_02634d7a15.jpg',
  'https://live.staticflickr.com/5704/22410267477_303a090dcd_n.jpg',
  'https://live.staticflickr.com/683/22207558073_8ecdb7abc4_z.jpg',
  'https://live.staticflickr.com/5648/22603412144_8bd9ba19bd_n.jpg',
    'https://live.staticflickr.com/5704/22410267477_303a090dcd_n.jpg',
  'https://live.staticflickr.com/3769/12146825775_cb8ae5f7e4_z.jpg',
  'https://live.staticflickr.com/7098/13183170974_451bd93d65.jpg',
  'https://live.staticflickr.com/4709/25401230397_a8a375d8cd.jpg',
  'https://live.staticflickr.com/5704/22410267477_303a090dcd_n.jpg',
  'https://live.staticflickr.com/4765/39533020694_3a8329e765.jpg',
  'https://live.staticflickr.com/5704/22410267477_303a090dcd_n.jpg',
  'https://live.staticflickr.com/4754/38432659650_9d6e5876a1.jpg',
  'https://live.staticflickr.com/4753/38432660740_78d6d34d89.jpg',
  'https://live.staticflickr.com/5704/22410267477_303a090dcd_n.jpg',
  'https://live.staticflickr.com/4654/39345481745_1be0a0098c.jpg',
  'https://live.staticflickr.com/4719/38432661400_f53017f598.jpg',
  'https://live.staticflickr.com/4665/38432665950_12d8d33002.jpg',
  'https://live.staticflickr.com/4677/40243327101_965347ed63.jpg',
  'https://live.staticflickr.com/5704/22410267477_303a090dcd_n.jpg',
  'https://live.staticflickr.com/4665/38432665950_12d8d33002.jpg'
]
var imgOnClick = function(e, imgConfig) {
  console.log('img clicked!', e, imgConfig)
}
var panelHTMLSetter = function(imgConfig) {
  var htmlString = ''
  if (imgConfig && imgConfig.payload && imgConfig.payload.title) {
    htmlString += '<div class="photo-block__panel__title">'+ imgConfig.payload.title +'</div>'
  }
  return htmlString
}
var box = new PhotoGridBox(insertPoint, imgs, imgOnClick, panelHTMLSetter)
box.setShowUnCompleteRow(true)

/*
 * examples
 */
// box.setShowUnCompleteRow(false)
// setTimeout(() => {
//   console.log('append!')
//   box.appendImgs([
//    'https://live.staticflickr.com/3769/12146825775_cb8ae5f7e4_z.jpg',
//    'https://live.staticflickr.com/7098/13183170974_451bd93d65.jpg',
//    'https://live.staticflickr.com/4709/25401230397_a8a375d8cd.jpg',
//    'https://live.staticflickr.com/5704/22410267477_303a090dcd_n.jpg',
//    'https://live.staticflickr.com/4765/39533020694_3a8329e765.jpg',
//    'https://live.staticflickr.com/5704/22410267477_303a090dcd_n.jpg',
//    'https://live.staticflickr.com/4754/38432659650_9d6e5876a1.jpg',
//    'https://live.staticflickr.com/4753/38432660740_78d6d34d89.jpg',
//    'https://live.staticflickr.com/5704/22410267477_303a090dcd_n.jpg',
//    'https://live.staticflickr.com/4654/39345481745_1be0a0098c.jpg'
//   ])
//   
//   // show the uncomplete row when there is no more image to load
//   box.setShowUnCompleteRow(true)
// }, 3000)
// 
// setTimeout(() => {
//   // remove the view and the eventListener by calling destroy method
//   console.log('destroy!')
//   box.destroy()
// }, 6000)
// 
// setTimeout(() => {
//   // it is possible to make the object alive again with appendImgs method
//   console.log('append again!')
//   box.appendImgs(imgs)
// }, 9000)
// box.setImgOnClick(() => {
//   console.log(123)
// })
// box.setPanelHTMLSetter(function (imgConfig) {
//   var htmlString = ''
//   if (imgConfig && imgConfig.payload && imgConfig.payload.title) {
//     htmlString += '<div class="photo-block__panel__title">'+ imgConfig.payload.title +'123</div>'
//   }
//   return htmlString
// })
              
            
!
999px

Console