### Install Dependencies
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/build-and-distribution.md
Install project dependencies using npm. This command should be run after cloning the repository.
```bash
npm install
```
--------------------------------
### Install Flickr Justified Gallery with npm
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/build-and-distribution.md
Use this command to install the gallery using npm, the Node Package Manager.
```bash
npm install flickr-justified-gallery
```
--------------------------------
### Start Development Server
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/build-and-distribution.md
Starts the development server with watch mode. The server rebuilds automatically on file changes and includes source maps. Access the application at http://localhost:3002.
```bash
npm run dev
```
--------------------------------
### Install Flickr Justified Gallery with pnpm
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/build-and-distribution.md
Use this command to install the gallery using pnpm, a performant package manager.
```bash
pnpm add flickr-justified-gallery
```
--------------------------------
### Install Flickr Justified Gallery with Yarn
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/build-and-distribution.md
Use this command to install the gallery using Yarn, a popular alternative package manager.
```bash
yarn add flickr-justified-gallery
```
--------------------------------
### Initialize FJGallery with Cleanup on Destroy
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/events.md
This example shows how to set up event listeners during gallery initialization and remove them when the gallery is destroyed. It uses `onInit` to add a listener and `onDestroy` to remove it, ensuring proper cleanup.
```javascript
let galleryInstance;
fjGallery(document.querySelector('.fj-gallery'), {
itemSelector: '.fj-gallery-item',
onInit() {
galleryInstance = this;
window.addEventListener('custom-event', handleCustom);
},
onDestroy() {
console.log('Gallery destroyed');
window.removeEventListener('custom-event', handleCustom);
}
});
// Later, destroy the gallery
fjGallery(document.querySelector('.fj-gallery'), 'destroy');
```
--------------------------------
### Install and Import fjGallery for CJS
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/README.md
Install fjGallery as a Node.js module using npm and import it into your application's entry point for use with bundlers like Webpack.
```bash
npm install flickr-justified-gallery
```
```javascript
import fjGallery from "flickr-justified-gallery";
```
--------------------------------
### Public Methods
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Reference guide for the 11 public methods available on FJGallery instances.
```APIDOC
## Public Methods
### init()
Initializes the gallery.
### appendImages()
Appends new images to the gallery.
### justify()
Triggers the justification layout process.
### resize()
Resizes the gallery to fit the current container.
### updateOptions()
Updates gallery options dynamically.
### destroy()
Destroys the gallery instance and cleans up.
### css()
Applies CSS styles to gallery elements.
### applyTransition()
Applies CSS transitions to gallery elements.
### onTransitionEnd()
Callback for when CSS transitions end.
### addToFjGalleryList()
Adds an instance to an internal list.
### removeFromFjGalleryList()
Removes an instance from an internal list.
```
--------------------------------
### Justified Layout Options Construction Example
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/types.md
Shows how to construct the justifiedOptions object within the justify method, gathering necessary values from the container and user options.
```javascript
// In justify()
const justifiedOptions = {
containerWidth: self.$container.getBoundingClientRect().width,
containerPadding: {
top: parseFloat(self.css(self.$container, 'padding-top')) || 0,
right: parseFloat(self.css(self.$container, 'padding-right')) || 0,
bottom: parseFloat(self.css(self.$container, 'padding-bottom')) || 0,
left: parseFloat(self.css(self.$container, 'padding-left')) || 0,
},
boxSpacing: self.options.gutter,
targetRowHeight: self.options.rowHeight,
targetRowHeightTolerance: self.options.rowHeightTolerance,
maxNumRows: self.options.maxRowsCount,
edgeCaseMinRowHeight: self.options.edgeCaseMinRowHeight,
edgeCaseMaxRowHeight: self.options.edgeCaseMaxRowHeight,
showWidows: self.options.lastRow !== 'hide',
};
const justifiedData = justifiedLayout(aspectRatios, justifiedOptions);
```
--------------------------------
### Log Layout Cycles and Measure Container Before Justify
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/events.md
This example shows how to use the `onBeforeJustify` callback to log each layout cycle and measure the gallery container's width before the justification algorithm runs. This is useful for debugging layout issues or performing pre-layout calculations.
```javascript
let layoutCount = 0;
fjGallery(document.querySelector('.fj-gallery'), {
itemSelector: '.fj-gallery-item',
onBeforeJustify() {
layoutCount++;
console.log('Layout cycle #' + layoutCount);
// Measure container size before layout
const rect = this.$container.getBoundingClientRect();
console.log('Container width:', rect.width);
}
});
```
--------------------------------
### FJGallery Usage Example
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/fj-gallery-class.md
Demonstrates how to create a new FJGallery instance, append images, update options, manually resize, and destroy the gallery. Ensure the container and item selectors are correctly defined in your HTML.
```javascript
const container = document.querySelector('.fj-gallery');
const gallery = new FJGallery(container, {
itemSelector: '.fj-gallery-item',
rowHeight: 300,
gutter: 10,
onInit() {
console.log('Gallery initialized');
},
onJustify() {
console.log('Layout recalculated');
}
});
const newItems = document.querySelectorAll('.new-item');
gallery.appendImages(newItems);
gallery.updateOptions({rowHeight: 400});
gallery.resize();
gallery.destroy();
```
--------------------------------
### Example Justified Layout Result
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/types.md
An example of the data structure returned by justifiedLayout, showing the arrangement of image boxes, widow count, and total container height.
```javascript
{
boxes: [
{top: 0, left: 0, width: 200, height: 150, row: 0},
{top: 0, left: 210, width: 250, height: 150, row: 0},
{top: 160, left: 0, width: 180, height: 140, row: 1},
// ... more boxes
],
widowCount: 1, // Last row has 1 item
containerHeight: 300 // Total height needed
}
```
--------------------------------
### onInit
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/events.md
Called after the gallery initialization completes. This event is useful for performing setup tasks, initializing related functionality, or tracking gallery creation after the gallery is ready and has processed its initial items.
```APIDOC
## onInit
### Description
Called after gallery initialization completes.
### Timing
- After `init()` method executes
- After `appendImages()` is called with initial items
- After gallery is added to global update loop
### Parameters
None
### Context
`this` refers to the FJGallery instance
### Use Cases
- Performing setup after gallery is ready
- Initializing related functionality
- Tracking gallery creation
### Example
```javascript
fjGallery(document.querySelector('.fj-gallery'), {
itemSelector: '.fj-gallery-item',
onInit() {
console.log('Gallery initialized with', this.images.length, 'images');
console.log('Instance ID:', this.instanceID);
console.log('Options:', this.options);
}
});
```
```
--------------------------------
### Import fjGallery using ESM CDN
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/README.md
Import fjGallery from a CDN using the ESM module format. This is a convenient way to include the library without local installation.
```html
```
--------------------------------
### Aspect Ratio Array Example
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/types.md
An array of numbers representing the width-to-height ratio for each image. Used by the better-justified-layout algorithm.
```javascript
[
1.5, // Image 1: 1.5:1 aspect ratio (landscape)
0.75, // Image 2: 0.75:1 aspect ratio (portrait)
1.0, // Image 3: 1:1 aspect ratio (square)
1.33 // Image 4: 1.33:1 aspect ratio
]
```
--------------------------------
### jQuery Plugin Event Initialization
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/events.md
Initialize the Flickr Justified Gallery using its jQuery plugin. This example demonstrates setting up basic events like `onInit` and `onJustify`.
```javascript
$('.fj-gallery').fjGallery({
itemSelector: '.fj-gallery-item',
onInit: function() {
console.log('jQuery gallery initialized');
},
onJustify: function() {
console.log('Layout updated');
}
});
```
--------------------------------
### Usage Example for Justified Layout Result
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/types.md
Demonstrates how to process the data returned by justifiedLayout to position elements and set the container height. Includes logic for handling the last row.
```javascript
const justifiedData = justifiedLayout(aspectRatios, justifiedOptions);
// Process layout
justifiedData.boxes.forEach((box, index) => {
positionElement(elements[index], box);
});
// Set container height
container.style.height = justifiedData.containerHeight + 'px';
// Handle last row alignment if needed
if (justifiedData.widowCount > 0) {
// ... apply last row alignment logic
}
```
--------------------------------
### Flickr Justified Gallery Usage with Options
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/types.md
Example of how to instantiate the Flickr Justified Gallery with a custom options object. This includes setting item and image selectors, row height, gutter, and a callback for justification.
```javascript
const options = {
itemSelector: '.fj-gallery-item',
imageSelector: 'img',
rowHeight: 320,
gutter: 10,
onJustify: function() { /* ... */ }
};
fjGallery(container, options);
```
--------------------------------
### Performance-Friendly Event Handling
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/events.md
Keep callbacks lightweight by caching data and avoiding heavy DOM operations. This example shows caching image references on initialization for later use.
```javascript
let cachedImages = null;
fjGallery(document.querySelector('.fj-gallery'), {
onInit() {
cachedImages = this.images; // Cache reference
},
onJustify() {
// Use cached reference instead of querying again
console.log('Total images:', cachedImages.length);
}
});
```
--------------------------------
### HTML Container with Multiple Data Attributes
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/configuration.md
An example of an HTML container with various data attributes used for gallery configuration. Note the kebab-case naming convention for data attributes in HTML.
```html
...
```
--------------------------------
### Image Data Object Creation Example
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/types.md
Illustrates how an image data object is created within the `appendImages()` function. It initializes properties from DOM attributes and includes a method to asynchronously load actual image dimensions, triggering a resize if they change.
```javascript
// Created in appendImages() for each item
const data = {
$item: itemElement,
$image: imageElement,
width: parseFloat(imageElement.getAttribute('width')) || false,
height: parseFloat(imageElement.getAttribute('height')) || false,
loadSizes() {
getImgDimensions(this.$image, (dimensions) => {
if (this.width !== dimensions.width || this.height !== dimensions.height) {
this.width = dimensions.width;
this.height = dimensions.height;
self.resize();
}
});
}
};
// Load dimensions immediately
data.loadSizes();
```
--------------------------------
### onJustify Callback Example
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/events.md
This snippet demonstrates how to use the onJustify callback to perform actions after the gallery layout is complete. It logs the container height and the number of visible images, and includes logic for lazy-loading images that are within the viewport.
```javascript
fjGallery(document.querySelector('.fj-gallery'), {
itemSelector: '.fj-gallery-item',
imageSelector: 'img',
onJustify() {
console.log('Layout complete');
console.log('Container height:', this.$container.offsetHeight);
console.log('Images visible:', this.images.filter(img => img.$item.offsetParent !== null).length);
// Lazy load images in viewport
this.images.forEach(imageData => {
const rect = imageData.$image.getBoundingClientRect();
if (rect.top < window.innerHeight) {
// Load image
loadImage(imageData.$image);
}
});
}
});
```
--------------------------------
### init()
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/fj-gallery-class.md
Initializes the gallery instance. It finds all gallery items, registers the instance for synchronized updates, and triggers the onInit callback if provided.
```APIDOC
## init()
### Description
Initializes the gallery by finding all gallery items and registering the instance with the global fjGallery update loop.
### Method
`init()`
### Parameters
None
### Return Value
`undefined`
### Behavior
1. Calls `appendImages()` with all items matching `itemSelector`
2. Adds instance to global `fjGalleryList` for synchronized resize handling
3. Triggers `onInit` callback if provided
```
--------------------------------
### Basic Implementation of Flickr Justified Gallery
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/INDEX.md
Demonstrates how to import the library, set up the HTML structure, include the CSS, and initialize the gallery with basic options.
```javascript
// Import
import fjGallery from 'flickr-justified-gallery';
// HTML structure
//
//
// ...
//
// Include CSS
import 'flickr-justified-gallery/dist/fjGallery.css';
// Initialize
fjGallery(document.querySelector('.fj-gallery'), {
itemSelector: '.fj-gallery-item',
rowHeight: 300,
gutter: 10
});
```
--------------------------------
### Method Chaining and Initialization
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/methods.md
Demonstrates how to initialize the gallery and chain method calls for updating options and resizing. Note that getter operations break the chain.
```APIDOC
## Method Chaining with jQuery
jQuery collections support method chaining:
```javascript
$('.fj-gallery')
.fjGallery('updateOptions', {rowHeight: 300})
.fjGallery('resize');
// But note: only method calls (string arguments) return the collection
// Getter operations return the actual value, breaking the chain
```
## Return Values
Most methods return `undefined`. The `fjGallery` function itself returns:
- The container element(s) array (for initialization)
- The method return value (if calling a method)
Example:
```javascript
// Initialization returns container array
const containers = fjGallery(document.querySelectorAll('.fj-gallery'), {...});
// Method call returns undefined (or method-specific return value)
fjGallery(container, 'resize');
```
```
--------------------------------
### Build Process Flow
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/build-and-distribution.md
Illustrates the steps involved in transforming source files into distributable formats using Rollup and Terser.
```text
Source Files (src/)
↓
Rollup
├─ Babel Transpilation (ES5)
├─ Dependency Resolution
├─ CommonJS Conversion
└─ Tree-shake annotations
↓
Intermediate Code
├─ ESM Format
├─ UMD Format
└─ CJS Format
↓
Terser (for .min.* files only)
├─ Minify
├─ Mangle
└─ Output source maps
↓
Distribution Files (dist/)
├─ fjGallery.esm.js
├─ fjGallery.esm.min.js
├─ fjGallery.js
├─ fjGallery.min.js
├─ fjGallery.cjs
├─ fjGallery.css
└─ Source maps (.map files)
```
--------------------------------
### css(el, styles)
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/methods.md
Gets or sets CSS styles on a given element within the gallery.
```APIDOC
## css(el, styles)
### Description
Gets/sets CSS styles on elements.
### Method
Direct invocation.
### Parameters
- **el** (HTMLElement) - Required - The element to apply styles to.
- **styles** (object) - Optional - An object containing CSS properties and values to set.
### Request Example
```javascript
// Get styles
const currentWidth = fjGallery.css(myElement, 'width');
// Set styles
fjGallery.css(myElement, {
'background-color': 'red',
'border': '1px solid black'
});
```
### Response
#### Success Response
- **string | HTMLElement** - Returns the computed style value if only `el` is provided, otherwise returns undefined.
### Response Example
`'100px'` (if getting width)
```
--------------------------------
### Update Flickr Justified Gallery Options
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/INDEX.md
Modify existing options of a fjGallery instance. For example, change the rowHeight after initialization.
```javascript
fjGallery(container, 'updateOptions', {rowHeight: 400});
```
--------------------------------
### Initialize Gallery with Event Callbacks
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/events.md
Pass event callbacks like `onInit` and `onJustify` when initializing the gallery using JavaScript.
```javascript
fjGallery(document.querySelector('.fj-gallery'), {
itemSelector: '.fj-gallery-item',
onInit() {
console.log('Gallery ready');
},
onJustify() {
console.log('Layout updated');
}
});
```
--------------------------------
### Get Dimensions of an Already Loaded Image
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/utility-functions.md
Demonstrates how to use getImgDimensions with an image that has already completed loading. The callback is invoked with the dimensions.
```javascript
const alreadyLoaded = new Image();
alreadyLoaded.src = 'https://example.com/image.jpg';
alreadyLoaded.onload = () => {
getImgDimensions(alreadyLoaded, (dimensions) => {
console.log('Ready:', dimensions);
});
};
```
--------------------------------
### init()
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/methods.md
Initializes the gallery. This method is typically called automatically upon gallery creation.
```APIDOC
## init()
### Description
Initializes the gallery (called automatically).
### Method
Internal use, called automatically.
### Parameters
None
### Request Example
(Not typically called directly by users)
### Response
#### Success Response
- undefined
### Response Example
undefined
```
--------------------------------
### Get Dimensions of a Specific Image
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/utility-functions.md
Use getImgDimensions to retrieve the dimensions of an image element selected from the DOM. The callback logs the dimensions to the console.
```javascript
const img = document.querySelector('img');
getImgDimensions(img, (dimensions) => {
console.log('Image size:', dimensions.width, 'x', dimensions.height);
});
```
--------------------------------
### Initialization Flow
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/architecture.md
Describes the sequence of calls from user interaction to the creation and initialization of a new gallery instance.
```text
User calls fjGallery(container, options)
↓
fjGallery function checks for existing instance
↓
No instance? Create new FJGallery(container, options)
↓
FJGallery.constructor():
- Merge options (defaults → data attrs → user options)
- Debounce resize method
- RAF-schedule justify method
- Call init()
↓
init():
- Find all items via itemSelector
- Call appendImages() with found items
- Register with global fjGalleryList
- Fire onInit callback
```
--------------------------------
### Internal Usage of domReady in fjGallery
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/utility-functions.md
Provides an example of how the domReady function is used internally within the fjGallery.js file to update galleries when the DOM is ready.
```javascript
// In src/fjGallery.js:22-24
domReady(() => {
updateFjGallery(); // Update all registered galleries when DOM ready
});
```
--------------------------------
### CSS Style Object Examples
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/types.md
Objects used to define CSS properties and values for gallery elements. Can be used for positioning, sizing, transitions, or display properties.
```javascript
{
position: 'absolute',
transform: 'translateX(10px) translateY(20px) translateZ(0)',
width: '200px',
height: '150px'
}
```
```javascript
{
'transition-property': 'transform',
'transition-duration': '0.3s'
}
```
```javascript
{
display: 'none'
}
```
```javascript
{
position: '',
transform: '',
transition: '',
width: '',
height: ''
}
```
--------------------------------
### Initialize FJGallery and Access Instance
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/fjGallery.md
Demonstrates how to initialize fjGallery on a container element and subsequently access the gallery instance directly from the container's property to call methods like resize.
```javascript
const container = document.querySelector('.fj-gallery');
fjGallery(container, {itemSelector: '.fj-gallery-item'});
// Access instance directly
const instance = container.fjGallery;
instance.resize();
```
--------------------------------
### Initialize Basic Gallery
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/README.md
Use this snippet to initialize the gallery with basic configuration options like item selector and row height.
```javascript
fjGallery(document.querySelector('.fj-gallery'), {
itemSelector: '.fj-gallery-item',
rowHeight: 300
});
```
--------------------------------
### Flickr Justified Gallery Initialization and Method Call
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/methods.md
Shows how to initialize the fjGallery plugin, which returns an array of container elements. It also demonstrates calling a method like 'resize', which typically returns undefined or a method-specific value.
```javascript
// Initialization returns container array
const containers = fjGallery(document.querySelectorAll('.fj-gallery'), {...});
// Method call returns undefined (or method-specific return value)
fjGallery(container, 'resize');
```
--------------------------------
### Get Dimensions of a Loading Image
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/utility-functions.md
Shows how to use getImgDimensions with an image that is still in the process of loading. The callback will be executed once the image's natural dimensions become available.
```javascript
const img = new Image();
getImgDimensions(img, (dimensions) => {
// Called when img.naturalWidth is available
renderGallery(dimensions);
});
img.src = 'https://example.com/image.jpg';
```
--------------------------------
### Iterate Through Image Data in Callbacks
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/events.md
Access and process individual image data objects within the `this.images` array in callbacks to get image dimensions and DOM elements.
```javascript
onJustify() {
this.images.forEach((imageData) => {
console.log('Image size:', imageData.width, 'x', imageData.height);
console.log('Item element:', imageData.$item);
console.log('Image element:', imageData.$image);
});
}
```
--------------------------------
### Production Build
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/build-and-distribution.md
Generates a production-ready build of the project. This command should be used before deploying the application.
```bash
npm run build
```
--------------------------------
### HTML Container with Data Attributes
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/configuration.md
Example of an HTML container element with data attributes for configuring the gallery. Options are merged in order of precedence, with data attributes overriding defaults.
```html
...
```
--------------------------------
### Key Methods
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/INDEX.md
Reference for the core methods available to manage the Flickr Justified Gallery instance after initialization.
```APIDOC
## Gallery Methods
### resize()
#### Description
Recalculates the gallery layout to adapt to changes in container size or item dimensions.
### appendImages(items)
#### Description
Adds new images to the gallery and recalculates the layout. Accepts a single item or a collection of items.
### updateOptions(options)
#### Description
Updates the gallery's configuration options after initialization. The layout will be recalculated based on the new options.
### destroy()
#### Description
Removes the gallery instance, cleans up event listeners, and removes added DOM elements.
```
--------------------------------
### Package Entry Points (package.json)
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/build-and-distribution.md
Defines the main, module, unpkg, and style entry points for the library, catering to CommonJS, ESM, CDN, and CSS distribution.
```json
{
"main": "dist/fjGallery.cjs",
"module": "dist/fjGallery.esm.js",
"unpkg": "dist/fjGallery.min.js",
"style": "dist/fjGallery.css"
}
```
--------------------------------
### Initialize and Resize with jQuery
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/INDEX.md
Demonstrates initializing and resizing fjGallery using jQuery selectors. The gallery is applied to elements matching the '.fj-gallery' CSS class.
```javascript
$('.fj-gallery').fjGallery({...});
$('.fj-gallery').fjGallery('resize');
```
--------------------------------
### Initialize FJGallery and Log Initialization Event
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/events.md
This snippet demonstrates how to initialize the fjGallery and log a message to the console when the gallery is fully initialized. It accesses gallery properties like the number of images, instance ID, and options within the `onInit` callback.
```javascript
fjGallery(document.querySelector('.fj-gallery'), {
itemSelector: '.fj-gallery-item',
onInit() {
console.log('Gallery initialized with', this.images.length, 'images');
// Access gallery instance properties
console.log('Instance ID:', this.instanceID);
console.log('Options:', this.options);
}
});
```
--------------------------------
### JavaScript Runtime Configuration Update
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/configuration.md
Shows how to initialize the gallery with options and then update them later using the `updateOptions` method. This method merges new options with existing ones and recalculates the layout.
```javascript
const container = document.querySelector('.fj-gallery');
fjGallery(container, {itemSelector: '.item'});
// Later, change options
fjGallery(container, 'updateOptions', {
rowHeight: 400,
gutter: 15,
lastRow: 'center'
});
```
--------------------------------
### Get and Set Styles on DOM Element
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/fj-gallery-class.md
Use this method to retrieve the computed style of a DOM element or to apply multiple inline styles at once. When setting styles, it accepts an object of CSS property-value pairs.
```javascript
const padding = gallery.css(container, 'padding-top');
gallery.css(item, {
display: 'none',
position: 'absolute',
transform: 'translateX(10px) translateY(20px)'
});
```
--------------------------------
### Initialize Gallery
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/INDEX.md
Initializes a new Flickr Justified Gallery instance on a specified container element with given options.
```APIDOC
## Initialize Gallery
### Description
Initializes a new Flickr Justified Gallery instance on a specified container element with given options.
### Method
`fjGallery(container, options)`
### Parameters
#### Path Parameters
- **container** (string | HTMLElement) - Required - The CSS selector or DOM element representing the gallery container.
- **options** (object) - Optional - Configuration options for the gallery.
- **rowHeight** (number) - The target height for each row.
- **gutter** (number) - The spacing between images.
### Request Example
```javascript
fjGallery(container, {rowHeight: 300, gutter: 10});
```
```
--------------------------------
### Basic Usage of domReady
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/utility-functions.md
Demonstrates the basic usage of the domReady function to execute code once the DOM is ready, including initializing a gallery.
```javascript
// Basic usage
domReady(() => {
const gallery = document.querySelector('.fj-gallery');
if (gallery) {
fjGallery(gallery, {itemSelector: '.fj-gallery-item'});
}
});
```
--------------------------------
### css(el, styles)
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/fj-gallery-class.md
Gets computed style or sets inline styles on a DOM element. It can either retrieve the computed style value for a specific CSS property or apply multiple inline styles to an element.
```APIDOC
## css(el, styles)
### Description
Gets computed style or sets inline styles on a DOM element.
### Parameters
#### Path Parameters
- None
#### Query Parameters
- None
#### Request Body
- None
### Method
Not applicable (JavaScript function)
### Endpoint
Not applicable (JavaScript function)
### Parameters
- **el** (HTMLElement) - Required - DOM element to get/set styles on
- **styles** (string | Object) - Required - CSS property name (string to get), or object of property-value pairs to set
### Return Value
string (if getting computed style) or HTMLElement (if setting inline styles)
### Behavior
- If `styles` is a string: returns computed style value using `getComputedStyle()`
- If `styles` is an object: sets each property as inline style and returns element
### Example
```javascript
// Get computed style
const padding = gallery.css(container, 'padding-top');
// Set styles
gallery.css(item, {
display: 'none',
position: 'absolute',
transform: 'translateX(10px) translateY(20px)'
});
```
```
--------------------------------
### Gallery with Callbacks
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/README.md
Configure the gallery to execute a callback function when the layout is recalculated.
```javascript
fjGallery(container, {
onJustify() {
console.log('Layout recalculated');
}
});
```
--------------------------------
### Direct Instance Access and Methods
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/methods.md
Provides methods to directly control and query the FJGallery instance after initialization.
```APIDOC
## Direct Instance Access
Access the FJGallery instance directly for advanced use cases.
### Initialization Example
```javascript
const container = document.querySelector('.fj-gallery');
fjGallery(container, {itemSelector: '.fj-gallery-item'});
```
### Getting the Instance
The instance is available on the container element.
```javascript
const instance = container.fjGallery;
```
### Methods
- **`resize()`**
Triggers a recalculation of the gallery layout. Automatically called on window resize, orientation change, load, image append, and option updates.
- **`updateOptions(options)`**
Updates the gallery with new options. Accepts an object of options to modify.
- **`options`** (object) - Required - An object containing new configuration options.
- **`destroy()`**
Removes the gallery instance and cleans up event listeners.
### Properties
- **`images`** (Array) - An array containing data for each image in the gallery.
- **`options`** (object) - The current configuration options for the gallery.
- **`instanceID`** (string) - A unique identifier for this gallery instance.
### Example Usage
```javascript
// Get the instance
const instance = container.fjGallery;
// Call methods directly
instance.resize();
instance.updateOptions({rowHeight: 400});
instance.destroy();
// Access properties
console.log(instance.images);
console.log(instance.options);
console.log(instance.instanceID);
```
```
--------------------------------
### Tight, Responsive Layout Configuration
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/configuration.md
Use this configuration for a compact layout with minimal spacing between images and strict height control. It's responsive to window resizing.
```javascript
fjGallery(container, {
rowHeight: 200,
gutter: 5,
rowHeightTolerance: 0.15,
resizeDebounce: 50
});
```
--------------------------------
### Import domReady Utility
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/utility-functions.md
Shows how to import the domReady utility function from its module.
```javascript
import domReady from './utils/ready';
```
--------------------------------
### Initialize Flickr Justified Gallery
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/INDEX.md
Use this snippet to initialize a new fjGallery instance. Specify the container element and configuration options like rowHeight and gutter.
```javascript
fjGallery(container, {rowHeight: 300, gutter: 10});
```
--------------------------------
### fjGallery Initialization and Method Calls
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/fjGallery.md
The `fjGallery` function serves as the main entry point for initializing justified galleries and interacting with existing instances. It can be used to initialize a gallery on one or more DOM elements, or to call methods on an already initialized gallery.
```APIDOC
## fjGallery Function
### Description
Initializes a justified gallery on the provided DOM elements or calls a method on an existing gallery instance.
### Method Signature
```javascript
fjGallery(items, options, ...args)
```
### Parameters
#### `items`
- **Type**: `HTMLElement` | `HTMLElement[]` | `NodeList` | `jQuery`
- **Required**: Yes
- **Description**: DOM element(s) to initialize as galleries. Can be a single element, array of elements, NodeList, or jQuery collection.
#### `options`
- **Type**: `Object` | `string`
- **Required**: No
- **Default**: `undefined`
- **Description**: Configuration object for gallery options, or a method name string to call on an existing gallery instance.
#### `...args`
- **Type**: `any[]`
- **Required**: No
- **Description**: Additional arguments passed to method calls when `options` is a string (method name).
### Return Value
- **Type**: `HTMLElement[]` | `any`
- **Description**: Returns the array of initialized container elements, or the return value of a method call if a method name was passed as the `options` parameter.
### Options Object (when `options` is an Object)
```javascript
{
itemSelector: '.fj-gallery-item', // string
imageSelector: 'img', // string
gutter: 10, // number | {horizontal: number, vertical: number}
rowHeight: 320, // number
rowHeightTolerance: 0.25, // number (0 to 1)
maxRowsCount: Number.POSITIVE_INFINITY, // number
edgeCaseMinRowHeight: 0.5, // number
edgeCaseMaxRowHeight: 2.5, // number
lastRow: 'left', // 'left' | 'center' | 'right' | 'hide'
transitionDuration: '0.3s', // string | false
calculateItemsHeight: false, // boolean
resizeDebounce: 100, // number
onInit: null, // function | null
onDestroy: null, // function | null
onAppendImages: null, // function | null
onBeforeJustify: null, // function | null
onJustify: null, // function | null
}
```
See [Configuration Reference](../configuration.md) for detailed documentation of each option.
```
--------------------------------
### Creating and Accessing Layout Boxes
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/types.md
Demonstrates how to generate justified layout data and iterate through the resulting boxes to access their properties.
```javascript
const justifiedData = justifiedLayout(aspectRatios, justifiedOptions);
// justifiedData.boxes is an array of these objects
justifiedData.boxes.forEach((box) => {
console.log(`Box at (${box.left}, ${box.top}), size: ${box.width}x${box.height}, row: ${box.row}`);
});
```
--------------------------------
### Include CSS Locally
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/build-and-distribution.md
Link to the local CSS file for styling the gallery. Ensure the path is correct relative to your HTML file.
```html
```
--------------------------------
### Call resize() Method
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/methods.md
Recalculates the gallery layout. Use this when the window size changes.
```javascript
// Recalculate layout on window resize
fjGallery(container, 'resize');
```
--------------------------------
### jQuery Integration
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/README.md
Initialize the gallery using jQuery syntax. This is useful if your project already uses jQuery.
```javascript
$('.fj-gallery').fjGallery({rowHeight: 300});
```
--------------------------------
### Initialize Flickr Justified Gallery with Vanilla JavaScript
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/README.md
Use this snippet to initialize the gallery with vanilla JavaScript. Pass the gallery container elements and an options object to the fjGallery function.
```javascript
fjGallery(document.querySelectorAll('.fj-gallery'), {
itemSelector: '.fj-gallery-item'
});
```
--------------------------------
### FJGallery Class
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Documentation for the core FJGallery class, including its constructor, public methods, properties, and instance management.
```APIDOC
## FJGallery Class
### Constructor
Initializes a new instance of the FJGallery.
### Public Methods
Provides access to all public methods for managing the gallery instance.
### Properties
Details on instance properties and how they are managed.
```
--------------------------------
### Multiple Callbacks with domReady
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/utility-functions.md
Shows how to register multiple independent callback functions with domReady, each executing when the DOM is ready.
```javascript
// Multiple callbacks
domReady(() => console.log('First callback'));
domReady(() => console.log('Second callback'));
```
--------------------------------
### Rollup Build Commands
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/build-and-distribution.md
Provides essential npm scripts for development and production builds, linting, and fixing lint issues. Use `npm run dev` for development with a live server and `npm run build` for production.
```bash
# Development build with watch and dev server on :3002
npm run dev
# Production build
npm run build
# Lint source code
npm run lint
# Fix lint issues
npm run lint-fix
```
--------------------------------
### FJGallery Methods
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/fj-gallery-class.md
Provides methods to interact with an FJGallery instance after initialization, including adding images, updating options, manual resizing, and cleanup.
```APIDOC
## FJGallery Methods
### appendImages
#### Description
Appends new image elements to the gallery and updates the layout.
#### Parameters
- **newItems** (NodeList or HTMLElement[]) - A list of new image elements to add to the gallery.
### updateOptions
#### Description
Updates the gallery's configuration options and recalculates the layout.
#### Parameters
- **options** (object) - An object containing the options to update.
### resize
#### Description
Manually triggers a resize and justification of the gallery layout. Useful after manual DOM changes or window resizing.
### destroy
#### Description
Cleans up the gallery instance, removing event listeners and any added DOM elements to prevent memory leaks.
```
--------------------------------
### Configuration Options and Events
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Reference for all configuration options and events available for fjGallery.
```APIDOC
## Configuration Options
### Layout Options
- **rowHeight** (number) - Target height for rows.
- **gutter** (number) - Space between items.
- **rowHeightTolerance** (number) - Tolerance for row height adjustment.
### Display Options
- **itemSelector** (string) - Selector for gallery items.
- **imageSelector** (string) - Selector for images within items.
- **lastRow** (string) - How to handle the last row ('auto', 'justify', 'nojustify').
### Behavior Options
- **transitionDuration** (number) - Duration of CSS transitions.
- **calculateItemsHeight** (boolean) - Whether to calculate item heights.
### Performance Options
- **resizeDebounce** (number) - Debounce time for resize events.
- **maxRowsCount** (number) - Maximum number of rows.
## Events
- **onInit** - Triggered when the gallery is initialized.
- **onDestroy** - Triggered when the gallery is destroyed.
- **onAppendImages** - Triggered after images are appended.
- **onBeforeJustify** - Triggered before the justification process.
- **onJustify** - Triggered after the justification process.
```
--------------------------------
### Load More / Pagination Implementation
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/configuration.md
Implement a 'load more' feature by initially limiting the number of rows and then appending new images and updating options when a user action occurs.
```javascript
// Show first 2 rowsjGallery(container, {
maxRowsCount: 2
});
// User clicks "Load More"
function loadMore() {
const newItems = document.querySelectorAll('.new-item');
fjGallery(container, 'appendImages', newItems);
// Show 4 rows now
fjGallery(container, 'updateOptions', {
maxRowsCount: 4
});
}
```
--------------------------------
### Initialize Flickr's Justified Gallery
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/demo/index.html
Initializes the gallery on a specified set of elements. Use this to apply the justified layout to your image containers.
```javascript
fjGallery(document.querySelectorAll('.fj-gallery'), { maxRowsCount: 2, itemSelector: '.fj-gallery-item' });
```
--------------------------------
### Initialize Flickr Justified Gallery
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/fj-gallery-class.md
Initializes the gallery. This method finds all gallery items and registers the instance with the global fjGallery update loop.
```javascript
init()
```
--------------------------------
### justify()
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/methods.md
Calculates and applies the optimal image layout for the gallery.
```APIDOC
## justify()
### Description
Calculates and applies optimal image layout.
### Method
Direct invocation.
### Parameters
None
### Request Example
```javascript
fjGallery(container, 'justify');
```
### Response
#### Success Response
- undefined
### Response Example
undefined
```
--------------------------------
### UMD Entry Point with jQuery Support
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/utility-functions.md
The Universal Module Definition (UMD) entry point for fjGallery. It includes support for jQuery, enhancing the prototype and providing a `$.fn.fjGallery` plugin method.
```javascript
import global from './utils/global';
import fjGallery from './fjGallery';
const $ = global.jQuery;
if (typeof $ !== 'undefined') {
// Enhance FJGallery.prototype for jQuery compatibility
// Set up $.fn.fjGallery plugin
}
export default fjGallery;
```
--------------------------------
### Integrate Flickr Justified Gallery with jQuery
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/INDEX.md
Shows how to initialize and update the gallery using jQuery selectors and methods.
```javascript
$('.fj-gallery').fjGallery({
itemSelector: '.fj-gallery-item',
rowHeight: 300
});
$('.fj-gallery').fjGallery('updateOptions', {rowHeight: 400});
```
--------------------------------
### FJGallery Constructor
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/fj-gallery-class.md
Initializes a new FJGallery instance. This class manages the gallery's lifecycle, including loading, layout, and rendering.
```APIDOC
## FJGallery Constructor
### Description
Initializes a new FJGallery instance. This class manages the gallery's lifecycle, including loading, layout, and rendering.
### Method
```javascript
new FJGallery(container, userOptions)
```
### Parameters
#### Path Parameters
- **container** (HTMLElement) - Required - DOM element to use as the gallery container
- **userOptions** (Object) - Optional - User-provided options merged with defaults. See [Configuration Reference](../configuration.md)
### Properties
- **instanceID** (number) - Unique identifier for this gallery instance
- **$container** (HTMLElement) - The DOM element containing the gallery
- **images** (Array) - Array of image data objects, each containing `{$item, $image, width, height, loadSizes}`
- **options** (Object) - Current gallery options (merged defaults + data attributes + user options)
- **pureOptions** (Object) - Copy of original options
- **defaults** (Object) - Default option values
- **justifyCount** (number) - Counter incremented each time justify is called
```
--------------------------------
### onInit Callback Signature
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/types.md
Callback function executed immediately after the gallery has been initialized. The 'this' context refers to the FJGallery instance.
```typescript
(this: FJGallery) => void
```
--------------------------------
### Import fjGallery using ESM
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/README.md
Import fjGallery as a module in your browser using the ESM build. Ensure your targeted browsers support ES modules.
```html
```
--------------------------------
### Initialize Flickr Justified Gallery
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/INDEX.md
Initializes the gallery on a given DOM element with specified options. The instance is stored on the container and image elements.
```javascript
fjGallery(container, {
itemSelector: '.photo-item',
imageSelector: '.photo-img',
calculateItemsHeight: true, // Account for captions
rowHeight: 300,
gutter: 10
});
```
--------------------------------
### FJGallery Instance Management
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/architecture.md
Visualizes how the main fjGallery function creates and manages individual FJGallery instances, each responsible for a single container and its associated data and layout.
```text
┌─────────────────────────────────────────┐
│ fjGallery Function │
│ (Entry point - handles multiple DOM │
│ elements and method calling) │
└────────────┬────────────────────────────┘
│
├─ Creates ─→ FJGallery Instance #1
├─ Creates ─→ FJGallery Instance #2
└─ Creates ─→ FJGallery Instance #N
Each FJGallery instance:
- Manages one container element
- Maintains array of image data
- Handles layout calculations
- Applies CSS transforms to items
- Manages event callbacks
```
--------------------------------
### Call updateOptions() Method
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/methods.md
Updates gallery configuration and recalculates the layout. Pass an object with new options.
```javascript
// Update gallery configuration and recalculate
fjGallery(container, 'updateOptions', {
rowHeight: 400,
gutter: 15,
lastRow: 'center'
});
```
--------------------------------
### FJGallery Constructor
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/fj-gallery-class.md
Initializes a new FJGallery instance. The container parameter is a required HTMLElement, and userOptions is an optional object for custom configurations.
```javascript
new FJGallery(container, userOptions)
```
--------------------------------
### Key Options
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/INDEX.md
Reference for the configuration options available to customize the behavior and appearance of the Flickr Justified Gallery.
```APIDOC
## Gallery Options
### itemSelector
- **Type**: string
- **Default**: `.fj-gallery-item`
- **Description**: CSS selector for the elements that act as containers for each gallery item.
### imageSelector
- **Type**: string
- **Default**: `img`
- **Description**: CSS selector for the image elements within each item container.
### rowHeight
- **Type**: number
- **Default**: `320`
- **Description**: The target height in pixels for each row in the justified layout.
### gutter
- **Type**: number
- **Default**: `10`
- **Description**: The space in pixels between gallery items.
### lastRow
- **Type**: string
- **Default**: `left`
- **Description**: Controls the alignment of the last incomplete row. Options: `left`, `center`, `right`, `justify`, `hide`.
### transitionDuration
- **Type**: string
- **Default**: `0.3s`
- **Description**: The CSS transition duration for animations when the layout changes.
```
--------------------------------
### Layout Flow
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/architecture.md
Explains the steps involved in justifying the gallery layout, from calculating aspect ratios to applying CSS transforms and setting container height.
```text
justify() called (debounced via RAF)
↓
Fire onBeforeJustify callback
↓
Build aspect ratio array from images
↓
Call better-justified-layout() with:
- Aspect ratios
- Container width/padding
- Row height & tolerance
- Max rows, gutter spacing, etc.
↓
Receive box positions and sizes
↓
Handle last row alignment if needed
↓
Apply RTL adjustments if isRtl=true
↓
For each image:
- Apply CSS transform (position)
- Set width
- Enable transition if not first justify
↓
If calculateItemsHeight:
- Measure actual item heights
- Adjust for captions
↓
Set container height
↓
Fire onJustify callback
```
--------------------------------
### fjGallery Options Object
Source: https://github.com/nk-o/flickr-justified-gallery/blob/master/_autodocs/api-reference/fjGallery.md
Defines the configuration options for initializing a fjGallery instance. These options control various aspects of the gallery's layout and behavior.
```javascript
{
itemSelector: '.fj-gallery-item', // string
imageSelector: 'img', // string
gutter: 10, // number | {horizontal: number, vertical: number}
rowHeight: 320, // number
rowHeightTolerance: 0.25, // number (0 to 1)
maxRowsCount: Number.POSITIVE_INFINITY, // number
edgeCaseMinRowHeight: 0.5, // number
edgeCaseMaxRowHeight: 2.5, // number
lastRow: 'left', // 'left' | 'center' | 'right' | 'hide'
transitionDuration: '0.3s', // string | false
calculateItemsHeight: false, // boolean
resizeDebounce: 100, // number
onInit: null, // function | null
onDestroy: null, // function | null
onAppendImages: null, // function | null
onBeforeJustify: null, // function | null
onJustify: null // function | null
}
```