Upon initial load, the masonry elements on the webpage collapse unexpectedly

Hey there!

I'm currently in the process of creating my own personal website - an online portfolio. While this is my first attempt at building a website from scratch, I must admit that I am quite new to HTML, CSS, JavaScript, and PHP. In fact, my knowledge of JavaScript and PHP is basic at best, so I have been relying on pre-made solutions to help me out. One such solution I am using is the Masonry grid layout library, but unfortunately, I've encountered some issues with it. The main problem I'm facing is that when the webpage is initially loaded, all the images collapse; however, upon refreshing the page, they align properly. I'm really stumped as to how to fix this issue.

For the layout of my project pages, I've utilized Masonry () with the intention of having library items neatly aligned in four rows. Each library item consists of a div containing an image and accompanying text. These divs are floated to the right.

<div class="item img">  
    <a href="image1.jpg">
        <img src="image1.jpg"/>
        <p>caption</p>
    </a>
</div>

All the images vary in height, and the image width is dependent on the column width. The column width and gutter spacing are set using elements, which are defined as a percentage of the browser window width.

CSS for image sizing:

.item img {
    max-width: 100%;
    height: auto;
}

HTML and CSS for defining column width and gutter spacing elements:

<div class="col_width"></div>   
<div class="gut_width"></div>

.col_width, .item {
    width: 22.5%;
}

.gut_width {
    width: 2%;
}

The Masonry script, placed just before the closing body and html tags:

<script src='masonry.js'></script>
<script>
var container = document.querySelector('#masonry');
var masonry = new Masonry(container, {
    gutter: container.querySelector('.gut_width'),
    itemSelector: '.item',
    columnWidth: container.querySelector('.col_width')
});
</script>

I suspect the issue lies in the variable height of the images, but it's possible that it could be related to the overall layout of the webpage itself.

Answer №1

The issue you are facing is related to the images not being loaded initially, causing them to have no dimensions when Masonry positioning is executed. The reason why it seems to work upon reloading is that the images are then cached.

To resolve this problem, try running the positioning script only after everything on the page has finished loading. One approach could be to hide all elements until the page is fully loaded, although implementing this may go beyond the scope of your current question.

<script>
    function masonry_init(){
        var container = document.querySelector('#masonry');
        var masonry = new Masonry(container, {
            gutter: container.querySelector('.gut_width'),
            itemSelector: '.item',
            columnWidth: container.querySelector('.col_width')
        });
    }
    window.onload = masonry_init;
</script>

References:

I have faced a similar issue myself!

For more information, check out MDN - GlobalEventHandlers.onload

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a React functional component that updates state when a specific window breakpoint is reached

Having an issue with my code when it hits the 960px breakpoint. Instead of triggering once, it's firing multiple times causing unexpected behavior. Can someone help me troubleshoot this problem? const mediaQuery = '(max-width: 960px)'; con ...

JavaScript - memory heap exhausted

Recently, I encountered an issue with my API written in Node.js. The purpose of this API is to read data from a MySQL database, write it into a CSV file, and allow users to download the file once the writing process is complete. Initially, everything was f ...

Tips for displaying previous values when discarding changes to a record in a material-ui table

How can I prevent changes from reflecting in a material-ui table when clicking on the X icon while editing a row? Is there a way to only save the edited record on the check (_) icon instead? Any suggestions or solutions would be greatly appreciated as I am ...

Can someone please explain the distinction between $http.get() and axios.get() when used in vue.js?

I'm feeling a little bit puzzled trying to differentiate between $http.get() and axios.get(). I've searched through various sources but haven't found any answers that fully satisfy me. Can someone please offer some assistance? ...

Executing AngularJS code that returns a promise within an event

In my run function, I am handling the $routeChangeSuccess event. My goal is to use $http to load some data and then change the $template. The issue here is that $http works asynchronously. I have attempted to return a promise inside the event, but it has ...

What is the best way to align two divs next to each other while keeping the second one centered with flexbox?

Here are my two div elements: <div class='container'> <div class='left'></div> <div class='centered'></div> </div> I am looking to center the second inner div and have the first inner ...

What is your approach to converting this jQuery code to ES6 syntax?

The concept involves gathering all the links and corresponding IDs, and hiding inactive content. When a link is clicked, the associated content should be displayed. The Structure <div class="navbar"> <nav> <ul class="navTabs"> ...

Capture and transform every alert into a notification

I have implemented Gritter for notifications across my website and am curious if there is an easy method to intercept all alert() messages triggered by scripts using jQuery, and then display the contents of the alert in a Gritter notification. Is there a ...

IE throws an exception when attempting to use Canvas as it is not supported

One of my challenges involves working with a Canvas Element: <canvas id="canvas" width="300" height="300"> Sorry, your browser does not support the Canvas element </canvas> In my JavaScript file, I have the following code: var ct= docum ...

What is the best way to add an element conditionally within a specific Vue Component scope?

I've been working on creating a Component for titles that are editable when double-clicked. The Component takes the specific h-tag and title as props, generating a regular h-tag that transforms into an input field upon double click. It's function ...

Mastering the Vue 3 Composition API: A guide to efficiently utilizing it across multiple Vue instances spread across different files

tl;dr What is the best way to import Vue3 in a base Javascript file and then utilize Vue's composition API in subsequent standalone files that will be loaded after the base file? I incorporate Vue to improve user interactions on specific pages like t ...

Having trouble displaying a local image in CSS using EJS

Hey there, I'm currently working with EJS. In my CSS file, I've added a background image but it's not showing up when the page loads. Strangely, if I use a hosted image, it works perfectly. Here is my directory structure: https://i.sstatic ...

Update the icon with the adjusted API information

I am currently working on a website that revolves around the theme of weather. I have reached a point in the development process where I need the icon to change according to the current weather conditions. let updateIcon = () => { let ic ...

Loop through the <li> elements and use jQuery to update the text

Check out this HTML setup: <div class="mydiv"> <ul> <li>Text 1</li> <li>Text 2</li> </ul> <ul> <li>Text 3</li> <li>Text 4</li> </ul> <ul> < ...

Changing base 64 into Mp3 audio format using PHP

I currently have an "audio" tag with a script (which is essentially a plugin) that receives and saves it as base64. This functionality is working properly. My goal now is to modify the script in order to send the base64 data to the server, convert it to m ...

JavaScript may fail to execute properly if the <!doctype html> declaration is not inserted in the correct syntax

While building a web page, I encountered an issue with my JavaScript code not working when using <!doctype html> or any type of <!doctype> at the top of the page. Can someone explain this error? After researching online, I learned that <!do ...

The alignment of the website design is off

I'm in the process of creating a custom template for my website and everything was going smoothly until I encountered an issue with the news bar placement. Instead of appearing below the navbar and welcome message bar, it's showing up above the n ...

Utilizing React Native to seamlessly integrate one JavaScript function into another

I am trying to integrate one javascript module into another. I recently downloaded a demo of GiftedMessanger After downloading the GiftedMessanger demo code, I incorporated all its dependencies into my own React Native (ios) project and successfully insta ...

Did my code effectively block an XSS attack?

Recently, I was informed that my website has vulnerabilities to XSS attacks. In an effort to improve security, I have implemented the htmlspecialchars method as a preventive measure. Here is the function I created: function _e($string){ return htmlsp ...

Nivo Slider's Interactive Image Mapping

I am encountering difficulties in integrating an image map into my nivo slider. The code I am currently using is shown below, and you can access the site by clicking on this link. Do you have any suggestions on how to resolve this issue? <div class=" ...