From 2b2abbf2aafc4d4d0a578b869921f6b89fb9615c Mon Sep 17 00:00:00 2001 From: HerrHase Date: Wed, 12 Jul 2023 22:21:33 +0200 Subject: [PATCH] adding img loading, height for container --- package.json | 2 +- src/masonry.js | 27 ++++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index fd9a360..995211d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@tiny-components/masonry", - "version": "0.2.0", + "version": "0.3.0", "description": "Masonry for Desktop and Mobile", "repository": { "type": "git", diff --git a/src/masonry.js b/src/masonry.js index bf4a1f0..2f198f8 100644 --- a/src/masonry.js +++ b/src/masonry.js @@ -17,6 +17,8 @@ class Masonry { */ constructor() { + this.height = 0 + // getting elements this.elements = document.querySelectorAll('.tiny-masonry__item-inner') this.container = document.querySelector('.tiny-masonry') @@ -24,7 +26,18 @@ class Masonry { // getting gap for calculate from grid this.gap = parseInt(getComputedStyle(this.container, 'gap').getPropertyValue('grid-gap').split(' ')[0]) - this.calculate() + // adding loaded event + this.elements.forEach((element) => { + const img = element.querySelector('img') + + if (img.completed) { + this.calculate() + } else { + img.addEventListener('load', () => { + this.calculate() + }) + } + }) window.addEventListener('resize', throttle(300, () => { this.calculate() @@ -50,6 +63,8 @@ class Masonry { } } + this.height = [] + for (let i = 0; i < this.elements.length; i++) { let marginTop = 0 @@ -83,6 +98,16 @@ class Masonry { } else { this.elements[i].parentElement.style.visibility = 'hidden' } + + // add complete height for element + this.height.push(parseInt(marginTop) + parseInt(this.elements[i].offsetHeight) + (this.gap * row)) + } + + // getting heighest height + this.height = Math.max(...this.height) + + if (this.height > 0) { + this.container.style.height = this.height + 'px' } } }