Masonry not initializing when inside a tab pane

Hello,

I have a masonry grid with images inside a tab pane. It doesn’t initialize when the tabpane is toggled and is active, I need to actually scroll the page for it to initialize. If I put the same masonry outside of the tabpane, it works fine.
This is what I get when the tabpane is activated and becomes visible:

An this is what I get when there is any interaction with the page:

I’ve seen this logged previously: Issue with multiple masonry in a page and how to initialise / destroy it . I wouldn’t mind having a line of code to trigger the init of the masonry as a hack, it’s something outside of my skillset right now.

Component like masonry, google maps, swiper and others that rely on the height of the element they are placed into will always have issues with tabs, modals, collapses, initially hidden elements.
On page load these elements have a height of 0 as they have a style of display: none; applied.

In your case, your tab 2 is hidden on page load and masonry component doesn’t know what its height is. You need to “refresh” the masonry component on tab show.

Example code, that will do the job:


<script>
    $('#navTabs1_2_tab').on('shown.bs.tab', function (e) {
    dmx.parse("masonry1.reflow()")
});
</script>

Where:

  • #navTabs1_2_tab is the ID of the nav tab button (note - not the tab content id!)
  • masonry1 is the ID of your masonry component
  • .reflow() refreshes the masonry

So put this code at the end of your page.

2 Likes

That worked perfectly, and the explanation makes a lot of sense. Thanks so much @Teodor!

Very helpful post!

This solution is also needed when the data source of the masonry element is cached.

1 Like

Hi @Teodor, I tried your suggestion but it didn’t work. Did anything change with the masonry component?

My example shows how to do this with Bootstrap 4, what version are you using?

Ah… I’m using version 5. Could you explain please how to do it with 5?

In Bootstrap 5 it’s a bit different. Your code should look like:

    <script>
        var tabEl = document.getElementById('navTabs1_2_tab')
        tabEl.addEventListener('shown.bs.tab', function (event) {
            dmx.parse("masonry1.reflow()")
        })
    </script>