Jekyll One

Fulltext Search

The xGallery module arranges images in evenly aligned rows as a block. Each row in such a block has the same height, but the images inside it can have different widths. This is the layout style you see on photo sites like Flickr or Google Photos.

The photos you take are usually a mix of landscape and portrait orientations. A simple grid would have to crop them or leave gaps. J1 xGallery solves this by keeping each image in its original shape and adjusting the widths so every row fills the page neatly.

15-60 Minutes to read

xGallery is the name of the J1 module. It is built on the open source library Justified Gallery (version 3.8.0), which J1 ships in an extended form (version 3.8.19) for the J1 Template version 2027.0.5.

The extended library can do more than the original one: a manage bar with an item list and an editor, saving the gallery items in the browser, search and sort, dialogs to rate, edit and remove single items, and drag-and-drop import of image files. These additions are marked as J1 extension on the following pages.

The idea of providing this documentation is not to simply copy the original Justified Gallery pages. For better readability and usability, all pages are restructured and enhanced by code examples or improved description texts.

Overview

The xGallery module arranges images in evenly aligned rows as a block. Each row has the same height, but the images inside a row can have different widths. Because every image keeps its original shape, landscape and portrait photos sit together without being cropped, and each row is stretched so it fills the full width of the page. This is the layout style you see on photo sites like Flickr or Google Photos.

xGallery

The xGallery API is the set of options, methods and events you can use from JavaScript to build and control a gallery. In the J1 Template you normally do not call this API yourself. Instead, you write a few YAML settings and the J1 Gallery adapter turns them into the correct JavaScript for every gallery on the page. Reading this manual is still useful, because the options you set in YAML use the same names as the API options described on the following pages.

In J1, a gallery is configured with three YAML files. They are merged together in the order shown below, and later files override earlier ones (this is called the inheritance chain). A key you leave out of a higher file is simply inherited from the file above it:

_data/modules/defaults/gallery.yml

The built-in default settings that apply to every gallery (for example the default rowHeight, the lightbox type, and the video player options). You normally do not edit this file.

_data/modules/gallery_control.yml

Your own settings, one entry per gallery (the gallery id, its type, the row height and gutters, the lightbox, and so on). Here you only need to write the values that differ from the defaults.

_data/modules/gallery_media.yml

The content of each gallery (the list of images or videos). Content is matched to a gallery by its id.

This three-file layout mirrors the Masonry module (masonry_control.yml / masonry_media.yml). The important idea is the split between configuration and content: gallery_control.yml says how a gallery should look and behave, gallery_media.yml says what it shows.

Every gallery has a type that decides what it shows:

image

A gallery of photos, optionally opened in a lightbox when clicked.

video

A gallery of videos. The extra key video chooses the source: html5 for self-hosted video files, or youtube for videos hosted on YouTube. The videos open in a lightbox and play in a VideoJS player. The lightbox is lightGallery by default, or PhotoSwipe when the gallery sets lightbox.type: ps.

A few keys tell J1 where the files are. They are set per gallery in gallery_control.yml:

id

The unique name of the gallery. The same id is used in gallery_media.yml (to find the content) and on the page (to place the gallery).

image_base_url

The folder of the images. The address of an image is built as <image_base_url>/<file>. For a video gallery this is the folder of the poster images (the still pictures shown on the tiles).

Give the full folder, for example /assets/image/my_gallery, not only a server address like http://localhost:40000. If the folder part is missing, every image address is wrong and the gallery stays empty. The browser console then shows a warning that names the gallery.

Older files may still use the key image_base_path. It works as a fallback, but image_base_url is the key to use.

video_base_path

The folder of the video files (only for video: html5). YouTube videos are written as full addresses in gallery_media.yml and need no folder.

enabled

Switches a gallery on or off. Only the value in gallery_control.yml counts. The enabled key in gallery_media.yml is ignored, so it cannot switch on a gallery that the control file switches off.

Features

The xGallery module for J1 provides the following key features:

Name Description

Justified rows

Images are placed into rows of equal height. Each row is stretched to fill the full page width, so there are no ragged edges on the right.

Keeps aspect ratio

Every image keeps its original shape. Landscape and portrait photos can be mixed freely without being cropped.

Responsive

When the browser window is resized, the gallery rebuilds itself to fit the new width.

Captions

An optional caption can appear over an image when the mouse is over it.

Lightbox support

A gallery can open its images or videos in a lightbox. J1 supports PhotoSwipe (ps), Lightbox2 (lb) and lightGallery (lg).

Image and video galleries

The same module builds galleries of photos, of self-hosted HTML5 videos, or of YouTube videos.

CSS filters

Optional CSS effects (grayscale, contrast, brightness) can be applied to the gallery images.

Manage bar (J1 extension)

A bar above the gallery with a title, the number of items, a button that opens a list of all items, and a button that opens an editor. Switched on with manage.enabled.

Save in the browser (J1 extension)

The gallery items can be saved in the browser (localStorage). Changes a visitor makes (add, edit, remove) are still there after a page reload. The items can also be exported to a JSON file and imported again.

Search and sort (J1 extension)

A search field and a sort list above the gallery. Only the matching items are shown, in the chosen order. Switched on with search.enabled.

Rate, edit and remove items (J1 extension)

Small buttons on every tile (and in the item list) open dialogs to give an item 1 to 5 stars, to change its title, description, category and tags, or to remove it. This works for images and for videos.

Drag-and-drop import (J1 extension)

In the editor, image files, whole folders, or image links from another page can be dropped onto a drop area to add many items at once.

Initialization

When the gallery’s HTML is on the page, xGallery is started by calling justifiedGallery() on the gallery element and passing the options you want:

// init xGallery
$('#myGallery').justifiedGallery({
  rowHeight: 150,
  margins:   1,
  lastRow:  'nojustify'
});

You can also react to the moment the layout is finished by listening for the jg.complete event:

$('#myGallery')
  .justifiedGallery({ rowHeight: 150 })
  .on('jg.complete', function () {
    // the gallery layout is ready
  });

Initialisation in J1 Template

In a J1 site you do not write the call above yourself. The J1 Gallery adapter (gallery.js) builds it for you from your YAML configuration.

This is what happens, step by step:

  1. When the site is built, J1 merges the three YAML files for every gallery (defaults, then your control settings, then the media content) and writes the HTML of all enabled galleries into one data file: <xhr_data_path>/index.html (default /assets/data/gallery/index.html).

  2. On the page, the macro gallery::<id>[] only places an empty placeholder (<id>_parent). When the page loads, the adapter fetches the HTML of that one gallery from the data file (AJAX) and puts it into the placeholder.

  3. The adapter waits until the page is ready and the HTML has arrived.

  4. It starts the library for every gallery whose enabled key is true in gallery_control.yml. It passes the keys of the gallery_options block (gutters becomes margins) and, when they are set, the J1 extension blocks storage, manage and search and the image folder image_base_url.

  5. When the layout is finished (the jg.complete event), the lightbox takes over the clicks:

    • lightGallery (lightbox.type: lg, the default) is attached by the adapter.

    • PhotoSwipe (ps) and Lightbox2 (lb) attach themselves, because the generated HTML already carries the attributes they look for. For PhotoSwipe galleries the adapter only checks that this worked and writes a warning to the browser console if it did not.

The gallery HTML is created when the site is built, not when the page is opened. After you change gallery_control.yml or gallery_media.yml, rebuild (regenerate) the site, or the browser still shows the old data.

The J1 extensions (manage bar, search bar, dialogs) are different: they are built in the browser at runtime and need no rebuild of the data file.

You can still reach a running gallery from JavaScript. The library stores its controller (the object that runs the gallery) on the gallery element, so you can get it with jQuery using $('#<your_gallery_id>').data('jg.controller').

To see the final settings a gallery runs with (after all three files are merged), type this in the browser console:

j1.adapter.gallery.getInstanceOptions('jgMegaCities')

A minimal gallery

To add a new image gallery to a J1 site you need three small steps.

Step 1 — describe the gallery in _data/modules/gallery_control.yml. Add a new entry to the list settings.galleries:

settings:
  galleries:
    - gallery:
      enabled:                  true
      id:                       myGallery
      type:                     image
      image_base_url:           /assets/image/my_gallery
      gallery_options:
        rowHeight:              200
        gutters:                3
      lightbox:
        type:                   ps

Watch the indentation. The keys of one entry (enabled, id, type, …​) start in the same column as the word gallery after the dash. If you indent them further, YAML puts them inside gallery: and J1 cannot find the id. The shipped files all use this style.

Step 2 — list the images in _data/modules/gallery_media.yml, using the same id:

settings:
  galleries:
    - gallery:
      id:                       myGallery
      images:
        - image:
          file:                 photo_1.jpg
          width:                1920
          height:               1280
          caption_text:         My first photo
          description:          <h3>My first photo</h3>
        - image:
          file:                 photo_2.jpg
          width:                1280
          height:               1920
          caption_text:         My second photo
          description:          <h3>My second photo</h3>

The image files must be in the folder named by image_base_url (here: /assets/image/my_gallery/photo_1.jpg, …​). The caption_text is shown on the tile, the description in the lightbox.

Step 3 — place the gallery on a page with the AsciiDoc macro and load the needed resources in the front matter of that page:

---
resources: [ gallery, photoswipejs ]
---
.My Gallery
gallery::myGallery[]

Use lightgallery instead of photoswipejs for galleries that keep the default lightbox (lg). Then rebuild the site.

Getting Started

This page shows how xGallery works with plain HTML and a small <script>. It is useful for understanding the options, even though in a J1 site you do not write this code by hand.

In J1 you configure a gallery through YAML, not through a <script> block. The options shown on this page (like rowHeight, lastRow and margins) are the same options you set under gallery_options in _data/modules/gallery_control.yml. The J1 Gallery adapter reads that YAML and calls justifiedGallery() for you. See the Initialisation in J1 Template section above.

Here we have a div, with the id basicExample, that holds a list of links pointing to full-size images. Inside each link there is a thumbnail. When

the library runs, the thumbnails are resized so they fill the whole row (this filling is called justification).

In J1 you never write this HTML yourself. J1 generates it from the image list in gallery_media.yml: one link plus one thumbnail per image. Both point to <image_base_url>/<file>, so the full image is also used as the thumbnail.

<div id="basicExample">
    <a href="path/to/image1.jpg">
        <img alt="caption for image 1" src="path/to/image1_thumbnail.jpg"/>
    </a>
    <a href="path/to/image2.jpg">
        <img alt="caption for image 2" src="path/to/image2_thumbnail.jpg"/>
    </a>
    ...
</div>

The most important option of the module is rowHeight (see Properties). Say you set a height of 160px — the algorithm then tries to build rows about that tall:

rowHeight

Justification may resize the images a little, so the real row height can end up slightly different from 160px. In other words, rowHeight is your preferred height (a lower bound). You can use the maxRowHeight option to put an upper limit on the row height; but remember that this option can crop images if they would have to be bigger to be justified.

The algorithm builds one row after another until it reaches the last one. That last row may not have enough images to fill the whole width. With the lastRow option you decide what happens: leave a blank space, justify the images anyway, or hide the last row if there would be too much empty space.

The next example uses smaller images (rowHeight: 70), does not justify the last row (lastRow: 'nojustify'), and uses a margin of 3px between images (margins: 3):

<div id="example" class="justified-gallery">
    <a href="path/to/image1.jpg">
        <img alt="caption for image 1" src="path/to/image1_thumbnail.jpg"/>
    </a>
    <a href="path/to/image2.jpg" title="Just in a dream Place">
        <img alt="caption for image 2" src="path/to/image2_thumbnail.jpg"/>
    </a>
    ...
</div>
<script>
    $('#example').justifiedGallery({
        rowHeight : 70,
        lastRow : 'nojustify',
        margins : 3
    });
</script>

In a J1 site you would write the same settings as YAML instead. Note that in J1 the spacing key is called gutters (the adapter maps it to the library’s margins option for you):

# _data/modules/gallery_control.yml
settings:
  galleries:
    - gallery:
      enabled:            true
      id:                 example
      type:               image
      image_base_url:     /assets/image/example       # folder of the images
      gallery_options:
        rowHeight:        70
        gutters:          3                           # J1 name for "margins"
        lastRow:          nojustify

The images themselves go into gallery_media.yml, under the same id:

# _data/modules/gallery_media.yml
settings:
  galleries:
    - gallery:
      id:                 example
      images:
        - image:
          file:           image1.jpg
          width:          1920
          height:         1280
          caption_text:   caption for image 1

Keep the keys of an entry (enabled, id, type, …​) in the same column as the word gallery after the dash. If you indent them further, YAML puts them inside gallery: and J1 cannot find the gallery.

Thumbnails

If your server stores the same image in several sizes (for example a small thumbnail for phones and a bigger one for retina screens), the plugin can load the best available size automatically, so the images always look sharp.

To switch this on you set sizeRangeSuffixes. For example, to match the Flickr suffixes you would use:

sizeRangeSuffixes: {
    100 : '_t', // used for images that are less than 100px on the longest side
    240 : '_m', // used for images between 100px and 240px on the longest side
    320 : '_n', // ...
    500 : '',
    640 : '_z',
    1024 : '_b' // used for images that are more than 640px on the longest side
}

The plugin then works out the path of a larger or smaller thumbnail just by changing the filename suffix. For example, from a thumbnail named path/to/image1_t.jpg it can load path/to/image1_b.jpg.

By default this feature is off — the plugin only uses the thumbnail you provide in the HTML. That default looks like this:

sizeRangeSuffixes: { }

In J1 you can set this option in YAML, too. Put it into the gallery_options block of the gallery; the adapter passes it on unchanged:

gallery_options:
  rowHeight:              150
  sizeRangeSuffixes:
    100:                  _t
    240:                  _m
    1024:                 _b

The smaller files must really exist on the server next to the full image (for example photo_1_t.jpg, photo_1_m.jpg, photo_1_b.jpg).

Properties

Properties (also called options) control how a gallery is built and how it behaves. You set them once, when the gallery is created. In J1 you write them as YAML under the gallery_options key of a gallery in gallery_control.yml; the adapter passes them on to xGallery.

Two small J1 details to keep in mind:

  • In J1 the spacing between images is written as gutters, not margins. The adapter maps gutters to the library option margins for you.

  • The library default for rowHeight is 120, but the J1 default (set in gallery.yml) is 150. A gallery that does not set rowHeight gets 150.

The table below lists the options you will use most often.

Property Default Description

rowHeight

150

The preferred height of each row, in pixels. Justification may change the real height a little, so treat this as your target height rather than an exact value.

maxRowHeight

false

An upper limit for the row height. Use false (or a negative value) to turn it off. A number sets the limit in pixels (e.g. 200). A percentage string sets it relative to rowHeight (e.g. "200%" means a row can be at most 2 * rowHeight).

[NOTE] ==== This option can crop images if they would need to be taller to be justified. ====

maxRowsCount

0

Limits how many rows are shown. Extra rows are hidden; if the page is made wider or narrower, more or fewer images fit and the number shown changes. 0 means no limit. This option does not make images smaller to fit more rows.

margins (J1: gutters)

1

The space between images, in pixels.

border

-1

The size of the border around the whole gallery. A negative value uses the same size as margins; 0 disables the border; any other number sets it in pixels.

lastRow

nojustify

What to do with the last row when it cannot fill the width. Use 'justify' to stretch it anyway, or 'hide' to hide it. With 'nojustify' the images keep their size and are aligned left; you can also use 'center' or 'right'.

captions

true

Show a caption over an image when the mouse is over it.

randomize

false

Show the photos in a random order.

filter

false

Show only some of the entries. Can be:

* false: no filtering (show everything). * a string: an entry is kept if entry.is(filter string) is true (see jQuery’s .is()). * a function: called with (entry, index, array); return true to keep the entry (see Array.prototype.filter).

sort

false

Sort the photos before showing them. Use false for no sorting, or a comparator function (see Array.prototype.sort()).

rtl

false

Right-to-left mode (lay the images out from right to left).

Advanced settings

These options are useful in special cases. Most galleries never need them.

Property Default Description

justifyThreshold

0.90

Controls when the last row is justified even though lastRow is nojustify. If row width (available space) is greater than this value (between 0 and 1), the row is justified anyway.

cssAnimation

true

Use CSS animations to fade the images in. With CSS animations it is easier to change the effect by overriding the CSS rules of xGallery. When true, the two options below are ignored.

imagesAnimationDuration

500

How long the image fade-in takes, in milliseconds. Ignored when cssAnimation is true.

captionSettings

{ animationDuration: 500, visibleOpacity: 0.7, nonVisibleOpacity: 0.0 }

Fine control over captions: the fade duration (ms), the caption opacity when visible (mouse over), and the opacity when not visible. Ignored when cssAnimation is true.

waitThumbnailsLoad

true

Wait for the thumbnails to load before building the layout. If your thumbnails have width and height attributes you can set this to false to build the layout immediately; the images then appear one by one as they load.

selector

a

Which direct children of the gallery are treated as entries. For performance reasons, entries must be direct children of the gallery element.

imgSelector

'> img',
'> a > img',
'> svg',
'> a > svg'

Given an entry, how to find its thumbnail image inside it.

extension

/\.[^.\\/]+$/

A regular expression that matches an image’s file extension. It is used when rebuilding a filename (for example together with sizeRangeSuffixes). Change it only if you need to match a specific extension.

refreshTime

200

How often (in milliseconds) the plugin checks whether the page width has changed. If it has, the layout is rebuilt.

refreshSensitivity

0

How many pixels the width may change without rebuilding the gallery.

rel

null

Rewrites the rel attribute of every link to this value. Often used to group images for a lightbox.

target

null

Rewrites the target attribute of every link. For example, with '_blank' (and no lightbox) images open in a new tab.

sizeRangeSuffixes

{ }

Filename suffixes for different thumbnail sizes, so the plugin can pick the best size automatically. Off by default. See Loading different thumbnail sizes.

thumbnailPath

undefined

A function that returns the thumbnail path for a given size, for full control over which file is loaded. It receives the current path, the target width and height, and the image element. If this is set, sizeRangeSuffixes is ignored.

[source, javascript] ---- $("#myGallery").justifiedGallery({ thumbnailPath: function (currentPath, width, height, image) { if (Math.max(width, height) < 250) { return currentPath.replace(/(.)(_[a-z])(\..*)/, "$1_small$2"); } else { return currentPath.replace(/(.*)(_[a-z])(\..)/, "$1_medium$2"); } } }); ----

triggerEvent

function

How the plugin fires its events (jg.complete, jg.resize, jg.rowflush). By default it calls $.trigger on the gallery element. You rarely need to change this.

Gallery settings in J1

The options above are only one part of a J1 gallery: they live in the gallery_options block. Every gallery entry in gallery_control.yml has a few more keys around it. The table shows them with their J1 default.

Key Default Description

enabled

false

Shows the gallery (true) or not (false). Set it to true for every gallery you want to use. Only the value in gallery_control.yml counts.

id

-

The unique name of the gallery. It must be the same in gallery_control.yml, in gallery_media.yml, and in the page macro gallery::<id>[].

type

-

image for a photo gallery, video for a video gallery.

image_base_url

-

The folder of the images (image galleries) or of the poster images (video galleries). Every image address is built as <image_base_url>/<file>. Use the full folder, for example /assets/image/my_gallery. YouTube galleries use //img.youtube.com/vi.

video

-

Video galleries only: html5 for your own video files, youtube for YouTube videos.

video_base_path

-

Video galleries with video: html5 only: the folder of the video files.

gallery_options

rowHeight: 150,
gutters: 1

The layout options of the library, described in the tables above.

lightbox.enabled

true

Opens a lightbox when an item is clicked. Leave it at true.

[WARNING] ==== With false, the current version renders no images at all for an image gallery (the gallery stays empty). Video galleries fall back to the lightGallery markup. ====

lightbox.type

lg

Which lightbox to use: lg (lightGallery), ps (PhotoSwipe) or lb (Lightbox2, image galleries only). Load the matching resource on the page: lightgallery for lg, photoswipejs for ps.

filters

see below

CSS effects for the images, see CSS filters.

photoswipe

see gallery.yml

Settings for galleries with lightbox.type: ps, for example the video player options (photoswipe.videoOptions). See the PhotoSwipe manual for all keys.

lightGallery

see gallery.yml

Settings for galleries with lightbox.type: lg: the plugins (lightGallery.plugins), the lightbox options (lightGallery.options) and the VideoJS player options (lightGallery.videojsOptions).

storage, manage, search

all off

The J1 extensions, described in the next sections.

You only need to write a key when its value is different from the default. Everything you leave out is taken from _data/modules/defaults/gallery.yml. Blocks are merged key by key: if you set only lightbox.type, the default lightbox.enabled: true is kept.

CSS filters

The filters block adds CSS effects to the images of a gallery.

Key Default Description

enabled

false

Switches the effects on. Without enabled: true none of the values below is used.

grayscale

1

Turns colors to gray. 0 = full color, 1 = completely gray.

contrast

0.8

The contrast. 1 = unchanged, smaller = less contrast.

brightness

0.4

The brightness. 1 = unchanged, smaller = darker.

filters:
  enabled:      true
  grayscale:    0.5
  contrast:     1
  brightness:   0.9

Storage settings (J1 extension)

The storage block saves the items of a gallery in the browser (localStorage, key jg_gallery_<id>). Saved items survive a page reload. This is useful when visitors add, edit or remove items with the manage bar, or when a gallery gets its items from JSON files instead of gallery_media.yml.

Key Default Description

enabled

false

Saves the gallery items automatically every time the layout is finished. A gallery with the manage bar (manage.enabled: true) can save items without this key; then the items are saved only when the visitor changes something.

key

null

The name of the browser storage entry. null means jg_gallery_<id>.

exportOnComplete

true

false = never save automatically; the items are saved only on request.

autoRestore

true

When the visitor changed the items (added, edited, rated, removed), the saved items replace the items of gallery_media.yml on the next page load. Set false to always show the items of gallery_media.yml.

mergeMode

false

How Import works: false replaces all items, true adds only the items that are not in the gallery yet.

reloadOnClear

true

After Clear Gallery the page is reloaded, so the gallery is built from gallery_media.yml again.

addClasses

[]

CSS classes given to items that are added by the editor. A gallery with lightGallery (lightbox.type: lg) needs [lg-item] here, so the new items open in the lightbox. PhotoSwipe galleries need nothing.

preload

false

JSON item files that are loaded into the gallery on every page load. Use a single file name or a list. Works only for a gallery whose images list in gallery_media.yml is empty. Items are never loaded twice, and items the visitor added are kept.

preloadUrlBase

/assets/data/apps/
xGallery/playlists/
lists

The folder of the preload files. File names that start with / or http(s):// are used as they are.

The easiest way to create a preload file: build the gallery in the browser with the editor, press Export Gallery, and save the downloaded file into the preload folder.

Manage bar settings (J1 extension)

The manage block builds a manage bar above the gallery. The bar shows a title with the number of items, a button on the left that opens the item list, and a button on the right that opens the editor. While the list or the editor is open, the gallery itself is hidden. Press the button again, click the title, or press Esc to close it.

The editor offers:

  • a drop area for image files, folders and image links,

  • a field to paste the link of one image,

  • a list of galleries on the server to import,

  • the buttons Export Gallery, Import Gallery and Clear Gallery (Clear Gallery first downloads a backup file).

manage:
  enabled:          true
  title:            My Photos
  showItemTools:    true

Bar and screens

Key Default Description

enabled

false

Builds the manage bar, the item list and the editor.

title

null

The title in the bar. null shows the gallery id.

showCount

true

Adds the number of items to the title, for example My Photos (12).

showListButton

true

Shows the left button (open or close the item list).

editButton

true

Shows the right button (open or close the editor).

listDeleteButton

true

Shows a remove button in every row of the item list. It removes the item at once, without asking.

listSource

auto

Where the item list (and the number in the title) comes from. auto = the saved items, or the items on the page while nothing is saved yet. store = saved items only. dom = items on the page only.

manageScreenHeight

535px

The height of the item list and the editor. A number means pixels; you may also write units like px, rem, em or vh (for example 60vh). Percent values are not supported. Longer content scrolls.

listUrl

index.json

The index file of the galleries offered by the import list of the editor. A plain file name is looked up in listUrlBase. false = no import list.

listUrlBase

/assets/data/apps/
xGallery/playlists/
lists

The folder of the index file and of the gallery files it names.

icons

{}

Replaces the four bar icons by name: playlist-show, playlist-hide, playlist-edit, playlist-edit-close. By default the icons of the J1 xVideo are used.

Item tools and dialogs

Every item can be rated (1 to 5 stars), edited (category, title, description, info link, image or video link, thumbnail or poster, issue date, tags) and removed. The buttons for this are shown in the rows of the item list and — when showItemTools is true — as small round buttons on every tile (on mouse over; always visible on touch devices). A new title is shown as the caption of the tile.

For video items the edit dialog shows Video Link, Poster Image and Video Size (for example 1280-720) instead of the image fields.

Key Default Description

showItemTools

false

Shows the rate, edit and remove buttons on every tile of the gallery.

itemRating

true

Offers the Set Media Rating dialog (star button).

itemEdit

true

Offers the Edit Media Settings dialog (edit button).

itemDelete

true

Offers the remove button on the tiles.

itemDeleteConfirm

true

Asks before an item is removed (dialog Remove Media Item). false removes at once.

categories

null

The choices of the Category list for images. null = a built-in list (Animals, Architecture, Art, Events, Family, Food, Landscape, Nature, People, Sports, Technology, Travel, Vehicles).

videoCategories

null

The same for video items. null = a built-in list (Animation, Comedy, Concert, Documentary, Education, Events, Family, Gaming, Movies, Music, Nature, News, Sports, Technology, Travel).

Rating, editing or removing an item marks the saved items as changed by the visitor. With storage.autoRestore: true (the default) the saved items are shown from the next page load on. Clear Gallery in the editor brings back the items of gallery_media.yml.

Drop area

The drop area at the top of the editor adds many images at once. You can drop image files, whole folders, or image links dragged from another browser tab. The browse …​ button opens a file picker instead.

A browser never tells a web page where a dropped file lives on your disk. So J1 maps a dropped file by its name to an address on your web server:

<image_base_url>/<dropBasePath>/<file>
<image_base_url>/<dropBasePath>/<folder>/<file>     (a whole folder dropped)

J1 then tries to load every address. Only images the server really delivers are added; the others are reported as "not found" below the drop area. In short: copy the image files into that folder on the server first, then drop them.

Key Default Description

dropArea

true

Shows the drop area in the editor.

dropBasePath

null

An optional sub folder below image_base_url for dropped files, for example sets/summer. null = the files are in image_base_url itself. false = local files are not mapped (only links can be dropped).

dropKeepFolders

true

When a folder is dropped, its name becomes part of the address.

dropMaxFiles

100

The maximum number of images per drop. 0 = no limit.

dropFallback

none

What happens to a file that is not found on the server. none = skip it. dataUrl = store the image itself inside the saved items (only for small images: the browser storage holds about 5 MB per site).

dropMaxDataUrlSize

100000

The largest file (in bytes) that dataUrl may store.

dropCloseOnSuccess

true

Closes the editor after a drop that added items without errors.

dropSettingsMenu

false

Shows a menu button (three dots) in the drop area. The menu lets you change image_base_url and dropBasePath for this gallery while the page is open, without editing the YAML files. Reset in the menu returns to the YAML values.

dropSettingsPersist

true

Remembers the values of that menu in the browser (key jg_dropbase_<id>) for the next visit.

Search settings (J1 extension)

The search block adds a search field and a sort list above the gallery (below the manage bar, when there is one). Only the matching items are shown. The search looks at the title, description, category, tags, type, caption and alt text of every item. Several words must all match; words in quotes, like "New York", are searched together. The search bar is hidden while the editor is open.

Key Default Description

enabled

false

Shows the search bar. It works for every gallery, also without the manage bar.

placeholder

(help text)

The gray help text inside the empty search field.

sort

true

Shows the sort list.

sortOptions

null

Which sort choices are offered, and in which order. null = all of them. The choices are: none (original order), addDate, addDateAsc, issueDate, issueDateAsc, title, category, description, rating, type.

defaultSort

none

The sort order on the first page load.

rememberSort

true

Remembers the chosen sort order in the browser for the next visit. The search text is not remembered.

showCount

true

Shows "n items found" while a search is active.

debounce

300

How long (in milliseconds) to wait after the last key press before searching. Enter searches at once, Esc clears the search.

search:
  enabled:        true
  sortOptions:    [ none, title, rating ]
  defaultSort:    title

Item file format (J1 extension)

Export Gallery, Import Gallery, storage.preload and the import list of the editor all use the same JSON format. A file is either a plain list of items, or an object with an items list (this is what Export Gallery writes):

{
  "meta_data": { "galleryId": "myGallery", "version": 1 },
  "items": [
    {
      "href":        "/assets/image/my_gallery/photo_1.jpg",
      "thumb":       "/assets/image/my_gallery/photo_1.jpg",
      "alt":         "My first photo",
      "width":       1920,
      "height":      1280,
      "title":       "Sunset",
      "category":    "Landscape",
      "rating":      4,
      "tags":        [ "sun", "sea" ]
    }
  ]
}

Only href is really needed; thumb defaults to href. Give width and height whenever you can — the layout needs the shape of the image.

The index file of the import list (listUrl) is a plain list of names and files:

[
  { "name": "Mega Cities", "file": "mega-cities.json" },
  { "name": "Old Times",   "file": "old-times.json" }
]

Commands

Commands let you control a gallery after it has been created. You call a command by passing its name (a string) to justifiedGallery() on the same element:

$('#myGallery').justifiedGallery('norewind');

In J1 the adapter creates the gallery for you, so you usually do not call commands. If you do need to, first get the element and then call the command on it, for example after adding new images to the page. You can reach a running instance with $('#<your_gallery_id>').data('jg.controller').

Command Description

(options object)

Calling justifiedGallery() again with an options object (for example { rowHeight: 200 }) updates the settings of an existing gallery and lays it out again with the new values.

norewind

Run Justified Gallery again, but only justify the newest images (the ones added since the last run). Because only the last images are looked at, any filter, sort or randomize you set only affects those new images. This is much faster, but be aware it does not touch the images that are already placed.

destroy

Remove the Justified Gallery layout from the element. The images go back to their normal, un-justified state and the plugin’s data is cleared.

Commands work only on a gallery that is already running. Calling a command on an element without a gallery stops with the error The argument must be an object (only destroy is silently ignored).

J1 commands (J1 extension)

The extended library understands more command names. Most of them need the browser storage or the manage bar of the gallery (storage.enabled or manage.enabled); without it they do nothing.

$('#jgMegaCities').justifiedGallery('storeExportFile');
Command Description

storeExport

Saves the items that are on the page now into the browser storage.

storeExportFile

Downloads the items as a JSON file (the same as Export Gallery).

storeImportFile

Opens the file picker to import a JSON file (the same as Import Gallery). Needs the manage bar.

storeRestore

Shows the saved items on the page again.

storePreload

Loads the files of storage.preload again (new items are added, nothing is loaded twice).

storeLoadIndex

Reads the index file of the import list again, for example after a new gallery file was put on the server. Needs the manage bar.

storeDecorate

Rebuilds the rate, edit and remove buttons on the tiles (or removes them when manage.showItemTools is false).

viewApply

Applies the current search text and sort order again.

viewReset

Clears the search and goes back to the default sort order (search.defaultSort).

storeDropInit

Sets up the drop area of the editor again. Needs the manage bar.

storeDropBaseReset

Forgets a folder that was changed in the drop menu and uses the YAML values again.

storeClear

Deletes the saved items (after downloading a backup file) and, with storage.reloadOnClear, reloads the page. The same as Clear Gallery.

J1 adapter methods (J1 extension)

The J1 Gallery adapter offers a few methods that are easier to use than the commands. You call them on j1.adapter.gallery and pass the id of the gallery. They are safe to call: if the gallery or the feature is not there, they simply return false, null or -1.

j1.adapter.gallery.searchGallery('jgMegaCities', 'tokyo');
j1.adapter.gallery.sortGallery('jgMegaCities', 'rating');
Method Description

getInstanceOptions(id)

Returns the final settings of a gallery after the YAML files were merged. Useful to check what a gallery really uses.

getStore(id)

Returns the browser storage of a gallery (or null). For example getStore(id).items() lists the saved items and getStore(id).count() counts them.

openItemsList(id), closeItemsList(id)

Opens or closes the item list of the manage bar.

closeEditGallery(id)

Closes the editor of the manage bar.

openRatingDialog(id, itemId)

Opens the Set Media Rating dialog for one item.

openEditDialog(id, itemId)

Opens the Edit Media Settings dialog for one item.

deleteItem(id, itemId, confirm)

Removes one item. With false as third value the item is removed at once. Otherwise the Remove Media Item dialog asks first (unless manage.itemDeleteConfirm is false).

searchGallery(id, text)

Searches the gallery and returns the number of items shown.

sortGallery(id, order)

Sorts the gallery, for example by title or rating (see Search settings).

resetGalleryView(id)

Clears the search and returns to the default sort order.

getGalleryView(id)

Returns the current search text, sort order and number of items shown.

importFiles(id, files)

Adds image files (for example from your own file input) the same way the drop area does.

getDropBasePath(id)

Returns the folder dropped files are mapped to.

setDropBase(id, imageBaseUrl, dropBasePath), resetDropBase(id), getDropBaseState(id)

Change, reset or show that folder from JavaScript — the same as the menu of the drop area.

Finding the id of an item

The dialog and delete methods need the itemId of an item. J1 creates this id for every item. The easiest ways to find it:

  • Open the browser developer tools and inspect a tile: a tile that was built from saved items carries the id in its attribute data-jg-item-id.

  • Or list all items with their ids in the console:

$('#jgMegaCities').data('jg.controller').store.serialize()
  .map(function (item) { return item.itemId + '  ' + item.href; });

Then, for example:

j1.adapter.gallery.openEditDialog('jgMegaCities', 'jg_1a2b3c4d');

Events

Events let your own code react to things that happen inside the gallery, such as the layout being finished. You listen for an event with jQuery’s .on() on the gallery element:

$('#myGallery')
  .justifiedGallery({ rowHeight: 150 })
  .on('jg.complete', function (e) {
    // runs when the gallery layout is ready
  });

The J1 Gallery adapter uses the jg.complete event internally: once a gallery’s layout is ready, the adapter attaches lightGallery (for galleries with lightbox.type: lg). PhotoSwipe and Lightbox2 attach themselves from the generated HTML; for PhotoSwipe galleries the adapter only checks that this worked. So in a normal J1 site you do not need to handle these events yourself.

Event Description

jg.complete

Fired when the whole gallery layout has been built.

jg.resize

Fired when the gallery has been resized (for example after the browser window changed width).

jg.rowflush

Fired each time a new row is ready.

jg.destroy

Fired after the gallery was removed with the command destroy.

J1 events (J1 extension)

The J1 extensions fire their own events on the gallery element. Most of them carry extra values, which you read from the event object (e).

Event Description

jg.storeRender

The items of the gallery were replaced (after an import, add, edit or remove). The adapter uses it to refresh lightGallery.

jg.storePreload

The files of storage.preload were loaded.

jg.storeIndex

The import list of the editor was filled from the index file.

jg.storeItemUpdate

One item was rated or edited.
Values: e.itemId, e.itemType (image or video), e.fields (the changed fields).

jg.storeItemDelete

One item was removed.
Values: e.itemId, e.href.

jg.viewChange

The search text or the sort order changed.
Values: e.query, e.sort, e.count (number of items shown).

jg.storeDrop

A drop (or a file picker selection) in the editor was processed.
Values: e.added, e.skipped (already in the gallery), e.failed (not found on the server), e.ignored (not an image), e.source.

jg.storeDropBase

The folder for dropped files changed (drop menu, method call, reset).
Values: e.base (the folder now used), e.override (true when changed at runtime), e.source.

Listening to events in J1

Two things are different in a J1 site:

  1. The gallery element is created after the page has loaded, when its HTML has arrived. Add your listener only when the gallery is running.

  2. The adapter stops every gallery event at the gallery element. A listener on document or on a parent element therefore never receives it. Always listen on the gallery element itself.

This small script waits until the gallery jgMegaCities is running and then reports every search:

var waitForGallery = setInterval(function () {
  var $gallery = $('#jgMegaCities');
  if ($gallery.data('jg.controller')) {
    clearInterval(waitForGallery);
    $gallery.on('jg.viewChange', function (e) {
      console.log('search: ' + e.query + ', items shown: ' + e.count);
    });
  }
}, 100);