Flickr-like Photo Grid In Vanilla JavaScript

Category: Gallery , Javascript , Layout | October 7, 2021
Author:tabsteveyang
Views Total:1,861 views
Official Page:Go to website
Last Update:October 7, 2021
License:MIT

Preview:

Flickr-like Photo Grid In Vanilla JavaScript

Description:

A Vanilla JavaScript library for rendering images in a responsive justified grid layout as you have seen on Flickr and Google Image Search.

How to use it:

1. Install and import the photo-grid-box-vanilla.

# NPM
$ npm i photo-grid-box-vanilla
import { PhotoGridBox } from 'photo-grid-box-vanilla';

2. Or load the stylesheet photo-grid-box-vanilla.min.css and JavaScript photo-grid-box-vanilla.min.js in the HTML document.

<link rel="stylesheet" href="css/photo-grid-box-vanilla.min.css" />
<script src="photo-grid-box-vanilla.min.js"></script>

3. Create a container to hold the photo grid.

<div id="container"></div>

4. Create an array of images to be present in the photo grid.

const imgs = [
      {
        src: '1.jpg',
        payload: {
          title: 'Image 1' 
        }
      },
      {
        src: '2.jpg',
        payload: {
          title: 'Image 2' 
        }
      },
     '3.jpg',
     // more images
];

5. Initialize the photo grid. That’s it.

const element = document.querySelector('#container');
const photoGrid = new PhotoGridBox(element, imgs);

6. Available parameters:

  • insertPoint: the element to hold the photo grid
  • imgs: array of images
  • imgOnClick: onClick event handler
  • panelHTMLSetter: a function that returns a HTML string for adding the children on the panel
  • rowGap: the height between each row
  • colGap: the change the width between each column
new PhotoGridBox(insertPoint, imgs, imgOnClick, panelHTMLSetter, rowGap, colGap);

7. More API methods.

// append more images to the photo grid
photoGrid.appendImgs(anotherImgArray);
// update the onClick event handler
photoGrid.setImgOnClick(function (e, imgConfig) {
  // do something
});
// update the panelHTMLSetter callback
photoGrid.setPanelHTMLSetter(function (imgConfig) {
  var htmlString = ''
  if (imgConfig && imgConfig.payload && imgConfig.payload.title) {  // use the parameter to reference the payload and create customized panel for each block
    htmlString += '<div class="photo-block__panel__title">'+ imgConfig.payload.title +'</div>'
  }
  return htmlString
});
// By default, the PhotoGridBox will hide the last row if the last row is not complete; to make it looks more natural when loading pictures chunk by chunk. When there is no more picture to load, or for any reason, you can use the method to cancel the feature.
photoGrid.setShowUnCompleteRow(true);
// destroy the photo grid
photoGrid.destroy();

You Might Be Interested In:


Leave a Reply