I am building a website to use as a portfolio for applying to university. I am quite bad with javascript and cannot get this to work even after reading all of the other similiar questions.
Basically masonry is initializing before the images have finished loading and this breaks the layout. You can see the issue on my website vladimirstamenov.com
I have been able ot replicate the issue 100% of the time by opening in private mode in firefox.
This is the solution I have attempted to use.
$(window).load(function(){
$('.grid').masonry({
columnWidth: 200,
itemSelector: '.portfolio-item'
});
});
In the above piece of code changing columnWidth to whatever does not affect my grid at all which makes me think it is not working at all.
My grid is structured like this:
<div class="row grid" data-masonry='{"percentPosition": true }'>
<div class="col-sm-6 col-md-4 portfolio-item">Image</div>
</div>
I have put the solution in a <script>
at the end of my body tag. Within that tag I also initialize "Animate On Scroll (AOS)" and have a short script that I need for my navbar. screenshot reference
Above that my javascript files are linked in the following order: JQuery > Bootstrap(5) > Masonry > AOS > Fancybox > Custom JS
Sorry if this is too much information. Thanks for your answers.
On your site, I can see that you have tried using the imagesLoaded plugin as follows:
//incorrect selectors
$('#container').imagesLoaded( function() {
$('.grid').masonry({
itemSelector: '.portfolio-item'
});
});
however, you do not have an element on the page with the ID 'container'. '#' is an ID selector. You should add a unique ID to the element containing your images, and update the selector to that. E.g.:
<div class="row pt-5 grid" id="gallery">
Furthermore, you do not have an element on the page with the class 'grid', so you should initialise Masonry on the #gallery too. As follows:
//updated selectors
$('#gallery').imagesLoaded(function() {
$('#gallery').masonry({
itemSelector: '.portfolio-item'
});
});
Finally, you can remove the inline instantiation of Masonry from your HTML, as you are initialising it using jQuery now. This bit:
data-masonry='{"percentPosition": true }' <-- not needed