Masonryjs Image Gallery Aligns Left On Page Refresh
So I have this image gallery which I displayed as Pinterest-style Masonry by using MasonryJS. Everything works fine but the problem is when I refresh the page. That is, when I refr
Solution 1:
Masonry has events we can take advantage of, like layoutComplete
. I used that to get masonry to load the images while hidden. Once the ready
event fires, we trigger Masonry's own layoutComplete
event to recalculate the elements. Then we run a callback once to reveal Masonry.
.modal-grid {
opacity: 0; /* jQuery will remove this later */transition: opacity; /* optional */
}
jQuery(window).on('load', function() {
/* Init your grid like normal but save it to a variable */const $grid = $('.modal-grid').masonry({
itemSelector: '.modal-grid-item',
gutter: 10,
isFitWidth: true
});
/*
Add a one time eventListener to just run on our hand-made "onLoad" event
*/
$grid.one('layoutComplete', function() {
/* and fade it in */
$grid.css('opacity', '1');
/*
If it is still happening, you can
add a setTimeout to delay the fade effect
*//**
let timeoutHandle;
timeoutHandle = setTimeout(function() {
$grid.css('opacity', '1')
// clear the timeout to make explicitly
// sure no extra timers are running
clearTimeout(timeoutHandle);
}, 1000);
*/
});
$(document).ready(function() {
// trigger the event when the document elements// are ready
$grid.trigger('layoutComplete');
});
});
If you wanna play around with it, you can check out the CodePen here.
Post a Comment for "Masonryjs Image Gallery Aligns Left On Page Refresh"