This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
--- | |
name: Image Gallery | |
category: Javascript | |
example: https://www.uspoloassnglobal.com/collections/Polo-Player-Inspired | |
description: Load the optimal image size for each tile: Get the clients screen resolution and multiply it by the dimensions of the tile. If client changes media query, then refresh these images. | |
--- | |
``` | |
*/ | |
import { BREAKPOINT } from '@/Scripts/constants' | |
import AOS from 'aos' | |
export function init(el, refeshItems) { | |
const galleryContainer = el | |
const galleryItems = [].slice.call(galleryContainer.querySelectorAll('.Collection-item')) | |
const resolution = window.devicePixelRatio | |
// Remove the photo tiles if media query changes. Not called on intial page load. | |
if (refeshItems) { | |
galleryItems.forEach(galleryItem => { | |
galleryItem.removeChild(galleryItem.querySelector('img')) | |
}) | |
} | |
galleryItems.forEach((lazyImage) => { | |
let entry = lazyImage | |
let imageWidth = Math.round(entry.offsetWidth * resolution) | |
let imageHeight = Math.round(entry.offsetHeight * resolution) | |
let imagePath = `${entry.dataset.img}?fit=fill&w=${imageWidth}&h=${imageHeight}&f=faces&q=75` | |
let imageAlt = entry.dataset.alt | |
let galleryImage = document.createElement('img') | |
galleryImage.alt = imageAlt | |
if (!entry.querySelector('img')) { | |
entry.appendChild(galleryImage) | |
galleryImage.src = imagePath | |
galleryImage.onload = function() { | |
galleryImage.classList.add('is-loaded') | |
} | |
} | |
}) | |
// Start the animate on scroll library | |
AOS.init() | |
// Reinit the photos when the media query changes from/to mobile, tablet, desktop. | |
// BREAKPOINT.MEDIUM.MIN === 769 | |
window.matchMedia(`(min-width: ${BREAKPOINT.MEDIUM.MIN}px)`).onchange = () => { | |
init(document.querySelector('[data-ondemand="gallery"]'), true) | |
} | |
// BREAKPOINT.LARGE.MIN === 1440 | |
window.matchMedia(`(min-width: ${BREAKPOINT.LARGE.MIN}px)`).onchange = () => { | |
init(document.querySelector('[data-ondemand="gallery"]'), true) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment